Powershell 日志记录错误

标签 powershell

我有一个简单的脚本来删除文件,我知道它可以更健壮,但就在这里

$LogFile = ".\deleteRegPol.log"

try
{
    Remove-Item "c:\test\new text document.txt" -force
    Add-Content $LogFile -Value "We ran the command"
}
catch [Exception]
{
    Add-Content $LogFile -Value $_
}
finally
{
}

当我尝试删除的文件不存在时,我在命令行上收到错误,但在我的日志文件中,它显示命令已运行。这告诉我没有抛出异常导致流转到 catch block 。为什么不呢?

最佳答案

当出现错误时,PowerShell 通常不会抛出异常。相反,它会将一条记录写入错误流,您可以将其重定向。要强制它抛出,有两种选择。一种是将全局错误首选项设置为停止:

$ErrorActionPreference = "Stop"

另一种是设置ErrorAction参数停止。接受所谓的公共(public)参数的 cmdlet 支持此功能,Remove-Item 执行以下操作:

Remove-Item "c:\test\new text document.txt" -force -EA "Stop"

要重定向错误流,您可以使用代码 2:

Remove-Item "c:\test\new text document.txt" -Force 2>> $LogFile

这会将错误附加到日志文件中。但是,如果您的选项是“停止”,则记录不会写入错误流。它只是包含在抛出的异常中。

关于Powershell 日志记录错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30792722/

相关文章:

powershell - 在 PowerShell 或批处理中格式化日志文件

c# - 如何使用 C# 获取 AppV 虚拟进程列表

powershell - SaltStack : run powershell script in a state

powershell - 如何使用 powershell 对 Active Directory 中的用户进行身份验证

powershell - 从命令行 PowerShell 7.2 传递哈希表参数

powershell - PS 中 "Access is denied"调用期间出现 "New-Item"错误

powershell - 如何在Powershell格式表中删除列之间的多余空间

string - 从PowerShell中的绝对路径获取相对路径

powershell - 在 PowerShell 中使用属性设置别名

powershell - 使用Powershell测试应用程序链接