Myr*_*rys 12 error-handling powershell active-directory powershell-3.0
我有一些看起来像这样的代码:
if (Get-ADUser $DN -EA SilentlyContinue) {
# Exists
} else {
# Doesn't Exist
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,当Get-ADUser DN无法找到用户时(这很好,这意味着没有采用对象名称),它会抛出并吐出错误.我知道它会失败,这很好,这就是为什么我有一个-ErrorAction到SilentlyContinue.不幸的是它似乎什么也没做......我仍然在脚本输出上得到barf.代码工作,由于控制台吐出错误,它只是丑陋.
Sha*_*evy 19
我发现没有吐出错误的唯一方法是使用filter参数:
if (Get-ADUser -Filter {distinguishedName -eq $DN} ) {
# Exists
} else {
# Doesn't Exist
}
Run Code Online (Sandbox Code Playgroud)
这是一个例外,你可以试着像这样抓住它:
$user = $(try {Get-ADUser $DN} catch {$null})
if ($user -ne $null) {
# Exists
} else {
# Doesn't Exist
}
Run Code Online (Sandbox Code Playgroud)
您希望捕获未找到的对象的异常,但您仍然希望因访问被拒绝等原因而失败,因此您需要指定要捕获的确切异常.
Try
{
Get-ADUser $DN -ErrorAction Stop
# Do stuff if found
}
Catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]
{
# Do stuff if not found
}
Run Code Online (Sandbox Code Playgroud)
要确定要在其他用例中捕获的异常类型,请导致异常,然后执行以下操作:
$Error[0].Exception.GetType().FullName
Run Code Online (Sandbox Code Playgroud)
它的输出进入:catch [在这里插入异常类型]