#PSTip How to get the email address of the currently logged-on user

We’ll use the [adsisearcher] type accelerator. The [adsisearcher] type is just a shortcut to the System.DirectoryServices.DirectorySearcher .NET class.

PS> [adsisearcher].FullName

We can use the accelerator to create a DirectorySearcher instance by supplying a LDAP filter. We can refine the search by changing other properties of the search object.

PS> $searcher = [adsisearcher]"(objectClass=user)"
PS> $searcher

CacheResults             : True
ClientTimeout            : -00:00:01
PropertyNamesOnly        : False
Filter                   : (objectClass=user)
PageSize                 : 0
PropertiesToLoad         : {}
ReferralChasing          : External
SearchScope              : Subtree
ServerPageTimeLimit      : -00:00:01
ServerTimeLimit          : -00:00:01
SizeLimit                : 0
SearchRoot               :
Sort                     : System.DirectoryServices.SortOption
Asynchronous             : False
Tombstone                : False
AttributeScopeQuery      :
DerefAlias               : Never
SecurityMasks            : None
ExtendedDN               : None
DirectorySynchronization :
VirtualListView          :
Site                     :
Container                :

For our purpose–finding the currently logged-on user’s email address–we want to pass the user name as the value for the SamAccountName property and ask for one result only. We will use the $env:USERNAME environment variable, and then query the mail property.

PS> $searcher = [adsisearcher]"(samaccountname=$env:USERNAME)"
PS> $searcher.FindOne().Properties.mail
Filed in: Columns, Tips and Tricks Tags: , , , ,

6 Responses to "#PSTip How to get the email address of the currently logged-on user"

  1. Juan Pablo Madriaga says:

    to another PC or to another user as I do?

    • PowerShellMag says:

      Hi Juan, can you clarify your question?

      • Juan Pablo Madriaga says:

        Sorry, I’m using google translator
        To do the same from a remote computer?
        Is it possible?

        • PowerShellMag says:

          You can get the logged on user on a remote system with WMI:

          (Get-WmiObject -Class Win32_ComputerSystem -ComputerName pc1).UserName

          Then use the method described in the tip to get his email address.

          • Juan Pablo Madriaga says:

            thank you very much

            $user = (Get-WmiObject -Class Win32_ComputerSystem -ComputerName pc1).UserName.Split(“”)

            $b = $user[1]

            $searcher = [adsisearcher]”(samaccountname=$b)”


  2. Youssef says:

    could you assist me to use this script for list of PCs

Leave a Reply

Submit Comment

© 8754 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: