我有一個簡單的腳本,它參考一個包含用戶帳戶 UPN 的 CSV 檔案,然后從 AD 組中洗掉這些用戶。
$CSVFile = Read-Host -Prompt 'Enter the name of the user CSV file (filename.csv)'
$Path = 'C:\scripts'
$UPNs = Import-Csv $Path\$CSVFile
$UIDs = Foreach ($UPN in $UPNs.userprincipalname) {
(Get-Aduser -filter {UserPrincipalName -eq $UPN}).SamAccountName
}
Remove-ADGroupMember "My-AD-Group" -Members $UIDs
問題是,如果 CSV 檔案包含不在 AD 中的 UPN,它將失敗并給出錯誤,指出“成員”不能為空值。一旦我洗掉了無效的 UPN,腳本就會正常作業。我想添加一種通過 UPN 的錯誤檢查,如果在 AD 中找不到,它不會中止整個函式。我希望它提供一個輸出,其中包含在 AD 中無法匹配的 UPN 串列。預先感謝您的任何建議。
uj5u.com熱心網友回復:
您可以切換策略以 1 對 1 處理它們 - 抑制來自Get-ADUserwith的錯誤-ErrorAction SilentlyContinue,然后使用if陳述句來測驗是否回傳了任何內容:
$CSVFile = Read-Host -Prompt 'Enter the name of the user CSV file (filename.csv)'
$Path = 'C:\scripts'
$UPNs = Import-Csv $Path\$CSVFile
foreach ($UPN in $UPNs.userprincipalname) {
$UID = (Get-ADUser -Filter {UserPrincipalName -eq $UPN} -ErrorAction SilentlyContinue).SamAccountName
if($UID){
Remove-ADGroupMember "My-AD-Group" -Members $UIDs
}
}
替代過濾掉陣列中的任何可能$null值,$UIDs然后再將其傳遞給Remove-ADGroupMember:
Remove-ADGroupMember "My-AD-Group" -Members $UIDs.Where({$_})
uj5u.com熱心網友回復:
如果您想向 PS 主機發送警告,顯示那些未找到的 UPN 并跳過null or white spaceCSV 上的元素,您可以使用:
$UIDs = Foreach ($UPN in $UPNs.userprincipalname)
{
if([string]::IsNullOrWhiteSpace($UPN))
{
continue
}
if(-not($usr = Get-ADUser -LDAPFilter "(UserPrincipalName=$UPN)"))
{
Write-Warning "- Not Found: $UPN"
}
else
{
$usr.DistinguishedName
}
}
Remove-ADGroupMember "My-AD-Group" -Members $UIDs
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/345256.html
