Script Repository


Output username of last user who logged on to computer

September 30, 2019
1150

The script outputs username of the last user who logged on to a computer to the Execution Log. To be able to use the script, create a Custom Command configured for the Computer object type that runs the script.

Edit Remove
PowerShell
$win32UserFilter = "NOT SID = 'S-1-5-18' AND NOT SID = 'S-1-5-19' AND NOT SID = 'S-1-5-20'" # Exclude well-known SIDs, such as NETWORK SERVICE

if (!(Test-Connection -ComputerName "%dNSHostName%" -Quiet))
{
    $Context.LogMessage("Cannot connect to computer '%dNSHostName%'", "Warning")
    return
}

# Get the last logged on user
$lastUser = Get-WmiObject -Class Win32_UserProfile -ComputerName "%dNSHostName%" -Filter $win32UserFilter | Sort-Object -Property LastUseTime -Descending | Select-Object -First 1

# Build filter to find the user
$userSID = $lastUser.SID
$filter = [Softerra.Adaxes.Ldap.FilterBuilder]::Create("ObjectSid", $userSID)

# Search user in AD
$domainName = $Context.GetObjectDomain("%distinguishedName%")
$searcher = $Context.BindToObject("Adaxes://$domainName/rootDSE")
$searcher.SearchFilter = $filter
$searcher.SearchScope = "ADS_SCOPE_SUBTREE"
$searcher.SetPropertiesToLoad(@("sAMAccountName"))

try
{
    $searchResultIterator = $searcher.ExecuteSearch()
    $searchResults = $searchResultIterator.FetchAll()
    
    if ($searchResults.Count -eq 0)
    {
        $Context.LogMessage("Cannot find user with SID '$userSID'. Probably, it is a local account.", "Warning")
        return
    }
    
    # Get Username
    $username = $searchResults[0].Properties["sAMAccountName"].Value
    $Context.LogMessage("Last logged on user: $username", "Information")
}
finally
{
    $searchResultIterator.Dispose()
}


Comments ( 0 )
No results found.
Leave a comment