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
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
That’s it. This will return the SID for the currently logged on user. Hope this helps.