VBScript: How-To Obtain The Currently Logged On User’s SID

I wanted a quick script to determine the current logged on user’s SID which I could then write into a new script for example to log each user’s SID at logon (during a logon script, etc).

The script I wrote below uses the environment variables USERNAME and USERDOMAIN to determine who the current logged on user is, and which domain they have logged on to. That information is then used to in a call to the getSid() function which connects to the local computer WMI service and queries it to retrieve the SID for the current user from the Win32_UserAccount wmi class.

First we want to find the current user and domain that they have logged on to:

'find current user & domain
Set wshShell = CreateObject("WScript.Shell")
strUsername = wshShell.ExpandEnvironmentStrings("%USERNAME%")
strDomain = wshShell.ExpandEnvironmentStrings("%USERDOMAIN%")

We’ll then show that information to confirm we’ve retrieved the right information:

WScript.Echo "Username: " & strUsername
WScript.Echo "Domain: " & strDomain

'use the user/domain information to retrieve the SID of the user and print it to the screen
WScript.Echo getSid()

The code above makes a call to a function called ‘getSid() so lets write that procedure. The procedure below creates an object with reference to the local machine’s WMI service, and then retrieves the SID information from the Win32_UserAccount class. It would be better programming practice to pass the username and domain variables to the function and use those parameters locally in the function, but this was written quickly to illustrate the idea.

Private Function getSid()
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set objAccount = objWMIService.Get("Win32_UserAccount.Name='" & strUsername & "',Domain='" & strDomain & "'")
getSID = objAccount.SID
End Function

That’s it. This will return the SID for the currently logged on user. Hope this helps.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s