2017-05-04 218 views
1

我是初學者的權力外殼。我需要編寫一個用於從活動目錄中獲取samccountname的電子郵件地址的命令。我已將所有samaccountnames存儲在Users.txt文件中。從Samaccountname獲取電子郵件地址

$users=Get-content .\desktop\users.txt 
get-aduser -filter{samaccountname -eq $users} -properties mail | Select -expandproperty mail 

請告訴我該如何繼續下去。我在這裏做錯了什麼。

回答

3

從文件中讀取後,$Users成爲用戶的集合。您無法將整個集合傳遞給過濾器,您需要一次處理一個用戶。你可以用一個foreach循環做到這一點:

$users = Get-Content .\desktop\users.txt 
ForEach ($User in $Users) { 
    Get-ADUser -Identity $user -properties mail | Select -expandproperty mail 
} 

這將輸出每個用戶的電子郵件地址到屏幕上。

根據評論,它也沒有必要使用-filter爲此,根據上述您可以直接發送samaccountname到-Identity參數。

如果你想在輸出發送到另一個命令(如出口CSV),你可以使用的foreach對象,而不是:

$users = Get-Content .\desktop\users.txt 
$users | ForEach-Object { 
    Get-ADUser -Identity $_ -properties mail | Select samaccountname,mail 
} | Export-CSV user-emails.txt 

在這個例子中,我們使用$_來表示當前項目管道(例如用戶),然後我們將命令的輸出傳送到Export-CSV。我以爲你可能也希望這種輸出具有samaccountname和mail,以便你可以交叉引用。

+2

您不需要使用'-filter'參數通過'sAMAccountName'檢索'ADUser'; '-Identity'參數將採用'sAMAccountName'作爲有效值:'Get-ADUser -Identity $ sAMAccountName -Properties mail |選擇對象 - 屬性郵件' –

+0

好點!我會修改我的答案。 –

相關問題