如何将此异常错误消息转换为我在 PowerShell 中的自定义消息?

How can I turn this exceptional error message into my custom message in PowerShell?

我正在编写应该验证活动目录中的用户并获取一些 AD 信息的脚本。我正在为这个脚本中的错误处理而苦苦挣扎:

$user = (Read-Host -Prompt 'Enter your network id').ToUpper()
#check if the user exists in the AD database
$userid= Get-ADUser $user | Select SamAccountName
$userid = $user

 if (($user -match $userid))  {

 Write-Host $user "exists in AD"
 }else{
 write-host "user cannot be found"
 }

如果使用该脚本的人输入错误的 userId(AD 中不存在),该脚本将抛出错误消息:

Get-ADUser : Cannot find an object with identity: 'DUMMY' under: 'DC=company,DC=com'.
At line:9 char:11
+ $memoid = Get-ADUser $user | Select SamAccountName
+           ~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (DUMMY:ADUser) [Get-ADUser], ADIdentityNotF 
   oundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management. 
   ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADUser
 

即使输入了错误的用户 ID,我也会收到

= DUMMY 存在于 AD

如何将此异常错误消息转换为我的自定义消息 -“AD 中不存在该用户”?提前谢谢你

您需要使用 try/catch 捕获异常 在错误消息中,它告诉我们“找不到该对象” 因此,您的第一种方法是在 If 语句中检查用户是否存在,然后将它们放入 try/catch 中,如下所示

try{

        $user = (Read-Host -Prompt 'Enter your network id').ToUpper()
        #check if the user exists in the AD database
        $userid= Get-ADUser $user | Select SamAccountName
        $userid = $user

         if (($user -match $userid))  {

         Write-Host $user "exists in AD"
         }else{
         write-host "user cannot be found"
         }

}
catch
{
    #Your Custom Message in case of the error is coming in Std Out . $_.Exception.Message will catch the exact error message. 
    "Error Message: "+ "$_.Exception.Message"

}

为此,最好不要使用 -Identity 参数(您在代码中使用 Get-ADUser $user 暗示)

尝试

$userID = Read-Host -Prompt 'Enter your network id'

# check if the user exists in the AD database
# this will either return an ADUser object or $null
$user = Get-ADUser -Filter "SamAccountName -eq '$userID'" -ErrorAction SilentlyContinue

if ($user) {
    Write-Host "$($user.SamAccountName) exists in AD" -ForegroundColor Green
}
else{
    Write-Host "user $($user.SamAccountName) cannot be found" -ForegroundColor Red
}

需要删除语句:$userid = $user。因为它确保您始终匹配。

接下来将对 Get-ADUser 的调用放在 Try/Catch 构造中以捕获错误。

$user = (Read-Host -Prompt 'Enter your network id').ToUpper()

#check if the user exists in the AD database

Try {
      $userid= Get-ADUser $user -EA "STOP" | Select SamAccountName
      Write-Host $user "exists in AD"
}
Catch {
#*** Process errors here ***
 write-host "user cannot be found"
 Exit
}

#Continue your script here

注意:我无权访问服务器,因此未经测试,但理论上应该可行! HTH