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!

4 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

    1. Your post is an old post now but it was exactly what i needed to get a single user’s UPN knowing their AD username.
      THANK YOU!!!

  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

  3. Thanks for steering me in the right direction. I modified this slightly to fit into a script for our off boarding process. I needed to convert username to user principal name.

    $listofusers = Read-host -prompt “Enter the name of Termed user (firstname.lastname)”

    $UPN = (get-aduser ($listofusers)).userprincipalname

Leave a Reply

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