Get a user's email address from the username via PowerShell and WMI? Get a user's email address from the username via PowerShell and WMI? powershell powershell

Get a user's email address from the username via PowerShell and WMI?


The simplest way is to useActive-Directory.

As you are using PowerShell tag and not PowerShell V2.0 you can use ADSI.

Clear-Host$dn = New-Object System.DirectoryServices.DirectoryEntry ("LDAP://WM2008R2ENT:389/dc=dom,dc=fr","jpb@dom.fr","Pwd")# Look for a user$user2Find = "user1"$Rech = new-object System.DirectoryServices.DirectorySearcher($dn)$rc = $Rech.filter = "((sAMAccountName=$user2Find))"$rc = $Rech.SearchScope = "subtree"$rc = $Rech.PropertiesToLoad.Add("mail");$theUser = $Rech.FindOne()if ($theUser -ne $null){  Write-Host $theUser.Properties["mail"]}

You can also use userPrincipalName instead of sAMAccountName in the filter, for userPrincipalName you can use user@domain form.


Using WMI : If you absolutly want to do it with WMI.

$user2Find = "user1"$query = "SELECT * FROM ds_user where ds_sAMAccountName='$user2find'"$user = Get-WmiObject -Query $query -Namespace "root\Directory\LDAP"$user.DS_mail

You can use the second solution localy on your server or from a computer inside the domain, but it's a bit more complicated to authenticate to WMI from outside the domain.


Using PowerShell 2.0

Import-Module activedirectory$user2Find = "user1"$user = Get-ADUser $user2Find -Properties mail$user.mail


Here's another possible way (original source):

PS> [adsisearcher].FullNameSystem.DirectoryServices.DirectorySearcherPS> $searcher = [adsisearcher]"(objectClass=user)"PS> $searcherCacheResults             : TrueClientTimeout            : -00:00:01PropertyNamesOnly        : FalseFilter                   : (objectClass=user)PageSize                 : 0PropertiesToLoad         : {}ReferralChasing          : ExternalSearchScope              : SubtreeServerPageTimeLimit      : -00:00:01ServerTimeLimit          : -00:00:01SizeLimit                : 0SearchRoot               :Sort                     : System.DirectoryServices.SortOptionAsynchronous             : FalseTombstone                : FalseAttributeScopeQuery      :DerefAlias               : NeverSecurityMasks            : NoneExtendedDN               : NoneDirectorySynchronization :VirtualListView          :Site                     :Container                :PS> $searcher = [adsisearcher]"(samaccountname=$env:USERNAME)"PS> $searcher.FindOne().Properties.mail


Not WMI, but this may do the job just as well:

PS> ([adsi]"WinNT://$env:USERDOMAIN/$env:USERNAME,user").Properties["mail"]