通过 PowerShell 更新 Active Directory

Updating Active Directory via PowerShell

你好,我对活动目录的更新脚本有疑问 我正在尝试使用 .csv 文档更新用户 我的理解很简单,但有一个错误,我无法找出为什么会发生。

我的脚本:

#Get CSV content
 $CSVrecords = Import-Csv "C:\scripts\test.csv" -Delimiter ";"
    
 #Create arrays for skipped and failed users
 $SkippedUsers = @()
 $FailedUsers = @()
    
 #Loop trough CSV records
 foreach ($CSVrecord in $CSVrecords) {
         $upn = $CSVrecord.UserPrincipalName
         $user = Get-ADUser -Filter "userPrincipalName -eq '$upn'"
         if ($user) {
                 try {
                         $user | Set-ADUser -Department $CSVrecord.Department -Company $CSVrecord.Company -ErrorAction STOP
                 }
                 catch {
                         $FailedUsers += $upn
                         Write-Warning "$upn user found, but FAILED to update."
                 }
         }
         else {
                 Write-Warning "$upn not found, skipped"
                 $SkippedUsers += $upn
         }
}

我尝试用于更新的日期:

UserPrincipalName Department Company
test.nikola@test.local Test 123

我收到的错误消息:找到用户,但更新失败

可能是我瞎了,但我找不到错误...

如评论中所述,您的 catch 块隐藏了 所有 终止异常。由于您从不输出或检查给定的异常,因此无法判断哪里出了问题。

改为:

try {
    $user | Set-ADUser -Department $CSVrecord.Department -Company $CSVrecord.Company -ErrorAction STOP
}
catch {
   $FailedUsers += $upn
   Write-Warning "$upn user found, but FAILED to update: $_"
}

在 catch 块内,$_ 将引用被捕获的异常,因此至少您现在有机会看到底层错误消息。