【问题标题】:How to discard errors of PowerShell ActiveDirectory cmdlets?如何丢弃 PowerShell ActiveDirectory cmdlet 的错误?
【发布时间】:2019-05-31 10:05:26
【问题描述】:

我正在编写一个 PowerShell 脚本(在 PowerShell 5.1 环境中),我需要列出文件夹权限中设置的组中的所有用户。但是有些组不相关,所以当我尝试对其进行 Get-ADGroupMember 时,我遇到了预期的错误。

为了放弃这个错误,我尝试了以下方法:

Get-ADGroupMember Fake_Group -Server ad.example.com 2>&1 $null
Get-ADGroupMember Fake_Group -Server ad.example.com 2>&1 | Out-Null

但是在这两种情况下,结果都是一样的:显示错误。

get-aduser : Cannot find an object with identity: 'Fake_Group' under 'DC=example.com'.
At line:1 char:1
+ Get-ADGroupMember Fake_Group -Server ad.example.com 2>&1 | ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Fake_Group:ADGroup) [Get-ADGroupMember], ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADGroupMember

所以我的问题是:为什么仍然显示这个错误?

然后,我怎么能放弃这个错误,或者有没有更好的方法来列出文件夹权限中设置的组中的用户,而不是仅仅尝试 Get-ADGroupMember 的整个结果Get-Acl 即使没有相关对象?

【问题讨论】:

    标签: powershell scripting


    【解决方案1】:

    因为 Out-Null 在这方面什么都不做,您需要使用 try/catch 语句,甚至可能需要添加 -ErrorAction Stop,因为并非 AD 命令中的所有错误都是终止错误:

    Try{
        Get-ADGroupMember $GROUPNAME -Server $SEVRER -ErrorAction Stop
        #The group is found, do whatever you want here
    }Catch{
        Write-Host "Some error occured"
    }
    

    【讨论】:

    • 我刚刚用 Start-Transcript 尝试了这个解决方案,如果在控制台中确实错误被 try..catch 隐藏, 转写的时候不是:/
    • 3 个问题:既然每次找到组时只需添加一行,为什么还要使用成绩单?你在成绩单中有什么错误?当我的答案仍然回答你原来的问题时,为什么要取消标记?
    • 1) 正如我所说,我正在编写一个脚本,所以我会做一些其他的事情,而不仅仅是 Get-ADGroupMember。目标是根据此脚本的输出编写报告。 2)我有“TerminatingError(Get-ADGroupMember):找不到具有身份的对象......” 3)这是一个missclick对不起,它确实回答了原来的问题
    • 回顾内存并使用下面的源备份,看起来这是设计使然。唯一的另一种方法是使用您自己的日志记录。成绩单捕获一切,这就是为什么它们在调试时如此方便。链接在这里:community.spiceworks.com/topic/…
    • 哦,我明白了.. 那么如何将每个命令的 stdout 和 stderr 重定向到 Bash 中的 { some commands } > file 2>&1 之类的文件?我在寻找时找到了 Start-Transcript,这就是为什么我实际上使用它来回答您的第一个问题。
    猜你喜欢
    • 2018-03-27
    • 2019-06-05
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 2020-04-27
    • 2021-10-25
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多