我正在使用從不同串列派生的用戶名串列向 AD 查詢用戶詳細資訊,這意味著并非所有用戶名都與 SamAccountName 完全匹配,例如可能會從末尾洗掉一個數字或字母。我可以讓精確匹配查找作業并輸出它找不到的名稱,但我想采用該串列名稱并通過 LDAPFilter anr 搜索運行它們以檢查模糊匹配。到目前為止,我有:
ForEach($User in $List){
Write-host "Now checking $User"
Try{
Get-ADUser -LDAPFilter "(anr=$User)" -Properties * |
select-object DisplayName,UserPrincipalName,mail,Enabled |
Export-CSV -Append $OutputFileResults -NoTypeInformation
Write-host "$User found successfully" -foregroundcolor Green
}
Catch{
$User | Export-CSV -Append $OutputFileFailed -NoTypeInformation
Write-host "$User not found" -foregroundcolor Red
}
}
目前,我得到的輸出只是說已成功找到用戶名,但沒有將任何內容寫入輸出檔案。
uj5u.com熱心網友回復:
Get-ADUser -LDAPFilter ... 當沒有找到用戶時不會拋出例外,所以說找到用戶名的事實告訴你什么都沒有 - 它會告訴你它是找到 0 還是 100 :)
顯式測驗它是否真的回傳任何東西以使其作業:
ForEach($User in $List){
Write-host "Now checking $User"
Try {
# search for matching users
$matchingUsers = Get-ADUser -LDAPFilter "(anr=$User)" -Properties * |
Select-object DisplayName,UserPrincipalName,mail,Enabled
if(-not $matchingUsers){
# no users found? throw to enter the catch block
throw
}
# otherwise proceed to export to CSV
$matching |Export-CSV -Append $OutputFileResults -NoTypeInformation
Write-host "$User found successfully" -foregroundcolor Green
}
Catch {
$User | Export-CSV -Append $OutputFileFailed -NoTypeInformation
Write-host "$User not found" -foregroundcolor Red
}
}
uj5u.com熱心網友回復:
Try/Catch in 不一定總是處理檢查是否回傳物件的最佳方式。我個人會改用 if/else 陳述句。在if條件中,我們將 Get-ADUser 的結果分配給$matchedUsers,然后檢查它是否為空。如果它不為空,那么我們繼續進入if塊。如果$matchedUsers為空,則else塊運行。
ForEach ($User in $List) {
Write-Host "Now checking $User"
if ($matchedUsers = Get-ADUser -LDAPFilter "(anr=$User)" -Properties *) {
$matchedUsers | Select-Object DisplayName, UserPrincipalName, mail, Enabled |
Export-Csv -Append $OutputFileResults -NoTypeInformation
Write-Host "$User found successfully" -ForegroundColor Green
}
else {
$User | Export-Csv -Append $OutputFileFailed -NoTypeInformation
Write-Host "$User not found" -ForegroundColor Red
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/362281.html
