通过PowerShell和WMI从用户名获取用户电子邮件地址?

12

我有一个用户的网络登录名。 从PowerShell和WMI中,可以获取该用户的有效电子邮件吗?请注意,登录名与电子邮件中的名称不同,因此我不能仅将登录名与电子邮件域组合。

3个回答

27

最简单的方法是使用Active-Directory。

由于您使用的是PowerShell标签而非PowerShell V2.0,因此可以使用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"]
}

你也可以在过滤器中使用userPrincipalName代替sAMAccountName,对于userPrincipalName,你可以使用user@domain的格式。

使用WMI:如果你绝对想要用WMI做到这一点。

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

您可以在本地服务器或域内计算机上使用第二种解决方案,但从域外验证到WMI要复杂一些。


使用PowerShell 2.0

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

1
哇,多么完整的答案!谢谢!WMI版本对我有用。我也会尝试2.0版本。 - Michael Kelley

15

这里是另一种可能的方法(原始来源):

PS> [adsisearcher].FullName
System.DirectoryServices.DirectorySearcher

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                :

PS> $searcher = [adsisearcher]"(samaccountname=$env:USERNAME)"
PS> $searcher.FindOne().Properties.mail

4
为了使这个答案生效,我只需要最后两行即可。 - Bård

0

虽然不是 WMI,但这也可以同样地完成工作:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接