Created
April 23, 2019 18:32
-
-
Save poiriersimon/0a3647953ac0cda72e8e25542e428f4a to your computer and use it in GitHub Desktop.
Powershell function to detect UPN for the currently logged user
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function Get-CurrentUPN | |
{ | |
$UserPrincipalName = $NULL | |
# | |
$UPNList = @() | |
$UPN = $Env:USERNAME | |
if($UPN -eq $NULL){ | |
$UPN = (whoami) | |
if($UPN -ne $NULL){ | |
$UPN = $UPN.split("\")[-1] | |
}else{ | |
$Proc = Get-CimInstance Win32_Process -Filter "name = 'powershell.exe'" | |
if($proc.GetType().BaseType.name -eq "Array"){ | |
foreach($process in $proc){ | |
$UPNList += Invoke-CimMethod -InputObject $process -MethodName GetOwner | select -ExpandProperty User | |
} | |
$UPN = $UPNList | select -first 1 | |
}else{ | |
$UPN = Invoke-CimMethod -InputObject $process -MethodName GetOwner | select -ExpandProperty User | |
} | |
} | |
} | |
#Find UPN | |
$strFilter = "(&(objectCategory=User)(SAMAccountName=$($UPN)))" | |
$objDomain = New-Object System.DirectoryServices.DirectoryEntry | |
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher | |
$objSearcher.SearchRoot = $objDomain | |
$objSearcher.PageSize = 1 | |
$objSearcher.Filter = $strFilter | |
$objSearcher.SearchScope = "Subtree" | |
$objSearcher.PropertiesToLoad.Add("userprincipalname") | Out-Null | |
$colResults = $objSearcher.FindAll() | |
[string]$UserPrincipalName = $colResults[0].Properties.userprincipalname | |
Return $UserPrincipalName | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment