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

问题描述

我正在编写脚本来验证活动目录中的用户获取一些 AD 信息。我正在努力解决此脚本中的错误处理:

pm.math.switch

如果有人使用该脚本将错误的 userId(在 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"
 }

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

= AD 中存在 DUMMY

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

解决方法

为此,最好不要使用 -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
}
,

您需要使用 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"

}
,

声明:$userid = $user 需要删除。因为它可以确保您始终匹配。

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

$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