Skip to content

Instantly share code, notes, and snippets.

@poiriersimon
Created April 23, 2019 18:32
Show Gist options
  • Save poiriersimon/0a3647953ac0cda72e8e25542e428f4a to your computer and use it in GitHub Desktop.
Save poiriersimon/0a3647953ac0cda72e8e25542e428f4a to your computer and use it in GitHub Desktop.
Powershell function to detect UPN for the currently logged user
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