Powershell | Get Current User Principle Name (UPN)


I had a need to write a Powershell script that would figure out what the current users UPN (User Principle Name) was. Believe it or not I was dumbfounded there wasn’t a good post on it anywhere.  So here is the code:


$strFilter = “(&(objectCategory=User)(SAMAccountName=$Env:USERNAME))”
$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()

$UPN = $colResults[0].Properties.userprincipalname


Enjoy, if you needed this and found it here please let me a comment, always glad to hear when these things help people out!

2 Replies to “Powershell | Get Current User Principle Name (UPN)”

  1. I know this is an old post but I was looking for something in a google search. Saw this, looked it over. Then I thought it could be done a bit cleaner provided the user has AD modules loaded. Just dropping here in case someone finds it useful.

    (get-aduser ($Env:USERNAME)).userprincipalname

  2. Here’s a better way, requires knowing where the person lives in AD:

    ([adsi]”LDAP://CN=John Doe,OU=SBSUsers,OU=Users,OU=MyBusiness,DC=smallbusiness,DC=local”).userPrincipalName

Leave a Reply

Your email address will not be published. Required fields are marked *