gpt4 book ai didi

powershell - -ErrorAction with Get-ADComputer 不隐藏错误

转载 作者:行者123 更新时间:2023-12-02 23:19:19 26 4
gpt4 key购买 nike

我刚刚开始使用 AD 研究 PowerShell,所以如果这个问题看起来很明显,我深表歉意。

我正在尝试检查列表中提供的哪些设备是否在 AD 中。到目前为止,我使用的代码来自: Powershell - verify object exists in AD

它工作得很好,但“-ErrorAction SilentlyContinue”实际上并没有抑制错误消息。我得到以下信息:


Get-ADComputer : Cannot find an object with identity: 'test' under:
'DC=test,DC=dom'.
At C:\Users\testaccount\Desktop\test.ps1:171
char:19
+ if (@(Get-ADComputer $target -ErrorAction SilentlyContinue).Count)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (test: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
}
}

我正在寻找的是抑制错误消息不再显示在控制台中 - 让脚本在错误时真正静默地继续。

我们将不胜感激任何帮助!

最佳答案

那么让我们谈谈发生了什么。

有两种类型的错误终止非终止

终止会停止命令的执行并抛出异常。非终止返回写出错误消息。

-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
}
}

关于powershell - -ErrorAction with Get-ADComputer 不隐藏错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56431019/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com