Powershell | Get Current User Principle Name (UPN)

Quicky,

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
$UPN

 

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

Advertisements

Tags: , , ,

About Eric

My name is Eric Weintraub. I am an IT Professional with over 12 years of real world experience. I currently work as a Senior IT Manager for a large software company that develops products for Information Technology workers. Professionally, I love what I do and it shows in my work. Personally, I enjoy technology as a whole. Enterprise Technology, Social Media, and Mobile technologies are all things I follow. I also love to play golf, go snowboarding, cook, love to eat, and read. Also big on photography, check out my recent photography at http://www.ericweintraubphotography.com and also Flickr: http://www.flickr.com/photos/ericweintraub/. As much as I don’t have a lot of free time, I always come across things that I believe could help others. I just wanted to be able to share what I find with others. Thanks for reading the blog, please setup a RSS feed and keep in touch! Eric Weintraub

One response to “Powershell | Get Current User Principle Name (UPN)”

  1. Joe Funk says :

    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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: