我刚刚开始使用AD来使用PowerShell,因此如果问题似乎很明显,我深表歉意。
我正在尝试检查列表中提供的哪些设备在AD中。到目前为止,我已经使用了以下代码: Powershell - verify object exists in AD
它可以正常工作,但是“ -ErrorAction SilentlyContinue”实际上并未抑制错误消息。我得到以下信息:
Get-ADComputer:在以下位置找不到标识为“ test”的对象:
'DC = test,DC = dom'。
在C:\ Users \ testaccount \ Desktop \ test.ps1:171
字符:19
+ if(@(Get-ADComputer $ target -ErrorAction SilentlyContinue).Count)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo:ObjectNotFound :(测试:ADComputer)[Get-ADComputer],ADIdentityNotFoundException
+ FullyQualifiedErrorId:ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADComputer
我正在使用的代码如下:
foreach ($target in $devicelist)
{
if (@(Get-ADComputer $target -ErrorAction SilentlyContinue).Count)
{
$existingdevices += $target
}
else
{
#display error notification
}
}
我要寻找的是抑制错误消息不再显示在控制台中-该脚本实际上在错误发生时继续静默运行。
任何人和所有帮助将不胜感激!
答案 0 :(得分:3)
因此,让我们谈谈正在发生的事情。
有两种类型的错误:终止和非终止。
终止会终止命令的执行并引发异常。非终止返回写出错误消息。
-ErrorAction
处理非终止错误
Try{}Catch{}
负责终止错误。
以您的情况
foreach ($target in $devicelist)
{
try{
if (@(Get-ADComputer $target -ErrorAction SilentlyContinue).Count)
{
$existingdevices += $target
}
else
{
#display non-terminating error notification
}
}catch{
#display Terminating error notification
}
}
答案 1 :(得分:0)
使用输出重定向:2> $Null
Get-ADComputer -Server BlahBlah -Identity ComputerThatDoesntExist 2> $Null