How to Get a User SID with PowerShell

Adam Bertram

Read more posts by this author.

Sometimes you need to find a user’s SID and when that happens, I go to PowerShell. Using PowerShell to get a user SID is easy once you’ve got the script and I just so have this for you!

In this article, you’re going to learn how to get a logged-in user’s SID with PowerShell by querying the HKCU registry hive.

Software vendors typically overlook a mass deployment method and just give you a registry file to import with all kinds of references to the HKCU registry hive.

The HKCU Ghost

If you’re doing a mass deployment of software (under LOCAL SYSTEM typically) the “HKCU hive” isn’t available to you.

Notice how I put the HKCU hive in quotes? I did this because, technically, there is no real HKCU hive. The HKCU hive is simply an alias to the HKU\%SID% hive with the SID being the SID of whatever user is currently logged onto the console.

I could write a few posts just on this topic or an entire course module *wink* on this topic but to be pragmatic I decided just to share one of the more important functions I use.

Introducing Get-LoggedOnUserSID

This PowerShell function (when executed as any user) will search the HKU registry hive for any key matching a GUID pattern and find the user SID.

It’s a pretty simple function but there’s one caveat I wanted to mention. On workstations, you’ll usually only see a single GUID key. Workstations can’t support multiple users, right? Technically, yes but I’ve seen instances where the hive won’t unload properly and you’ll see multiple SID keys there so don’t go dropping this function in and writing your script expecting only a single string to come back. I learned that lesson the hard way.

Also, if you run this on a terminal server you’ll get back all of the SIDs of all the users that are logged in. This can come in pretty handy for that as well.

function Get-LoggedOnUserSID {
    <#
        .SYNOPSIS
            This function queries the registry to find the SID of the user that's currently logged onto the computer interactively.
    #>
    [CmdletBinding()]
    param ()
    
    process {
        try {
            New-PSDrive -Name HKU -PSProvider Registry -Root Registry::HKEY_USERS | Out-Null
            (Get-ChildItem HKU: | where { $_.Name -match 'S-\d-\d+-(\d+-){1,14}\d+$' }).PSChildName
        } catch {
            Write-Error -Message "Error: $($_.Exception.Message) - Line Number: $($_.InvocationInfo.ScriptLineNumber)"
            $false
        }
    }
}

Subscribe to Stay in Touch

Never miss out on your favorite ATA posts and our latest announcements!

Looks like you're offline!