powershell - 通过管道处理错误以进行日志记录

标签 powershell error-handling pipeline error-logging

我想知道是否有人可以给我一些通过管道处理非终止错误的提示?
这是我想做的一个例子。

Get-ADUser -Filter {Enabled = 'False'} -Properties Modified | Where Modified -LT (Get-Date).AddDays(-30) | Remove-ADUser -Confirm:$false

基本上找到所有上次修改的时间戳少于30天的禁用用户,然后将其删除。
所以我要寻找的是如何处理和错误(如果发生),以便可以记录下来

我考虑过使用try catch,但是如果发生错误,则整个命令将停止。我希望它是一个非终止错误,以便它将继续处理找到的所有用户,但是然后有一种方法来查看是否存在任何错误,以便我可以记录他们

有什么建议?

最佳答案

您可以在没有Try-Catch构造甚至没有-ErrorAction的情况下使用-ErrorVariable。
因此,例如,您可以这样做:

Get-ADUser -Filter {Enabled = 'False'} -Properties Modified -ErrorVariable Get-ADuserErr |`
Where Modified -LT (Get-Date).AddDays(-30) -ErrorVariable Where-ObjectErr |`
Remove-ADUser -Confirm:$false -ErrorVariable Remove-ADuserErr
If ($Get-ADuserErr) {
Write-Output $Get-ADuserErr }
If ($Where-ObjectErr) {
Write-Output $Where-ObjectErr }
If ($Remove-ADuserErr) {
Write-Output $Remove-ADuserErr }

这样,您可以使用另一个变量来存储每个命令的错误,并获得默认的错误处理行为(通过$ ErrorActionPreference,默认情况下为“Continue”)。

同样,您的错误变量($ Get-ADuserErr,$ Remove-ADuserErr等)是可以通过管道传递到Out-File以将错误记录到文件中的对象。

更好的是,这些错误变量是“ErrorRecord”类型的对象,其对象具有一些属性,例如:TargetObject,Exception,InvocationInfo,fullQualifiedErrorID等。
因此,您可以进一步操作错误变量对象以准确记录所需的内容。

关于powershell - 通过管道处理错误以进行日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25045215/

相关文章:

azure - 我在 Azure 管道步骤中收到 "Bash wrote one or more lines to the standard error stream"

asp.net - 是否可以在管道的早期提前处理和结束请求?

ssl - 是否可以在不导航到 IIS :\SSLBindings 的情况下创建 SSLBinding

.net - 在 Windows 8 RTM 上的 .NET 应用程序中嵌入 Powershell v2.0

php - 关于stackify-api,数据未显示在stackify日志中

rust - 应用程序的错误处理 : how to return a public message error instead of all the chain of errors and tracing it at the same time?

asp.net - httpErrors 在本地计算机上显示 500 错误而不是 YSOD

python - One-Hot 编码训练和测试数据时形状不匹配。将 get_dummies 与管道一起使用时,Train_Data 比 Test_data 具有更多的虚拟列

azure - 无法使用 PS cmdlet Set-AzWebApp 更新 Azure 应用服务的 AppSettings

PowerShell 在逗号或空格后修剪姓氏