Search This Blog

Tuesday, June 19, 2012

Powershell: Get SID of all logged on users

This function will list store the SIDs of all logged on users in an array:


Function Get-LoggedOnUsersSID
{
    #Create empty array
    $CurrentUser = @()
    #Store all processes named 'explorer.exe' in $proc
    $proc = Get-WmiObject win32_process -computer $ENV:COMPUTERNAME `
    -Filter "Name = 'explorer.exe'"
    #Go through collection of processes and save information in
    #$temp, extract username and store in $CurrentUser
    ForEach ($p in $proc) { 
        $temp = "" | Select Computer, Domain, User 
        $temp.computer = $c
        $temp.user = ($p.GetOwner()).User 
        $CurrentUser += $temp.User
    }

        #Create empty array
    $SID = @()


    #Translates all usernames stored into SID
    ForEach ($element in $CurrentUser) {
        $objUser = New-Object `
        System.Security.Principal.NTAccount ` 
        ("DOMAIN", $Element)
        $strID = $objUser.Translate `
        ([System.Security.Principal.SecurityIdentifier])
        $SID += $strID.Value
    }
    
    #Set return value to $SID, array containing all SIDs
    Return $SID
}

Function call:
$AllSID = Get-LoggedOnUsersSID

NO GUARANTEE THAT THIS FUNCTION WORKS WITHOUT ANY ERRORS IN YOUR ENVIRONMENT - PLEASE TEST IT FIRST!

Sources
http://learn-powershell.net/2010/11/01/quick-hit-find-currently-logged-on-users/
http://community.spiceworks.com/how_to/show/2776

No comments:

Post a Comment