It's useful to be able to query a computer for the users that are logged on
locally. You can do this with Sysinternals' free PsLoggedOn utility, but sometimes
you want to use the information directly in a scripted task (e.g., contacting
users who are logged on to a terminal server that needs a reboot because of
a security patch). Although it's possible to execute the PsLoggedOn utility
and parse its output in a script for use in other scripts, I decided to see
whether I could gather the names of logged-on users by using a script instead
of relying on PsLogged-On.
How PsLoggedOn Works
I started by downloading and examining the C source code for the Ps-LoggedOn
utility to see how it determines locally logged-on users. The technique it uses
isn't complex and is fairly easy to implement by calling the methods in Windows
Management Instrumentation's (WMI's) StdRegProv class. An overview of the technique
PsLoggedOn uses is as follows:
- Enumerate the subkeys in the computer's HKEY_USERS registry subtree.
- For each subkey in the subtree that contains a SID value, determine whether
the subkey contains a Volatile Environment subkey. If it does, and if the
Volatile Environment subkey contains one or more values, then the user that
the SID represents is currently logged on.
- Convert the SID value into the corresponding username.
In Figure 1, the HKEY _USERS subtree is expanded
to show a subkey that has a SID value. You can also see that the subkey contains
a Volatile Environment subkey that contains values. Thus, you know that the
user represented by the SID S-1-5-21-299502267-1078145449-725345543-500 is currently
logged on. . . .

