Function Get-CurrentUser { <# .SYNOPSIS Gets the current user .DESCRIPTION Gets current logged-on user regardless of context .EXAMPLE Get-CurrentUser .INPUTS None .OUTPUTS System.Object #> [CmdletBinding()] Param() Begin {} Process { Try { # Get the username of the currently logged in user $objCS = Get-WmiObject -Class Win32_ComputerSystem $username = $objCS.UserName # Check if a user is logged in if ($username -eq $null) { Write-Output "No user currently logged in." } else { # Get the SID for the user $objUser = New-Object System.Security.Principal.NTAccount("$username") $strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier]).Value $result = [PSCustomObject]@{ Username = $username SID = $strSID } return $result } } Catch { Write-Error -Message $PsItem.Exception return $null } } }