powershell - PowerShell 中的异常日志记录

标签 powershell

我目前在我的 PowerShell 脚本中记录异常时遇到问题。我正在尝试将文件复制到 C:\Windows\System32,如果出错,我想在我的日志文件中添加一个错误行。到目前为止,我已经尝试过这两种方式。

示例 1:

$LogPath = "C:\Test.txt
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition

Copy-Item $scriptPath\Devcon.exe C:\Windows\System32 -ErrorAction SilentlyContinue -ErrorVariable $Errors

Foreach($error in $Errors)
{
    add-content -Path $LogPath -Value $($error.Exception) -Force
}

示例 2:

$LogPath = "C:\Test.txt
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition

Try{
    Copy-Item $scriptPath\Devcon.exe C:\Windows\System32
}
Catch [System.Exception]
{
    add-content -Path $LogPath -Value "There was an error why trying to copy the file." -Force
    add-content -Path $LogPath -Value $Error -Force
}

我可以将项目添加到日志文件中,因此我知道这不是文件的权限问题。我错过了什么?

最佳答案

我相信你得到的错误是非终止的。这就是为什么它不会在 catch block 中结束。

试试这个而不是你的 Copy-Item 行:

Copy-Item $scriptPath\Devcon.exe C:\Windows\System32 -ErrorAction Stop

Help on ErrorAction (MSDN) .

关于powershell - PowerShell 中的异常日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17531997/

相关文章:

powershell - 获取列表中每台计算机的序列号(Powershell)

python - Anaconda 提示 "Failed to create temp directory ' C :\temp\conda-<RANDOM>\' " error

python - 从 Python 执行 PowerShell 脚本的最佳方式是什么

powershell - 当我使用其他帐户登录 Windows 时,如何通过 PowerShell 获取 Azure 帐户的订阅?

windows - 安排Powershell脚本每小时运行一次

powershell - 使用 powershell 脚本制作批处理文件

powershell - Get-Content -Wait 在读取文件时锁定文件,防止 Add-Content 写入数据

json - 不知道如何在Powershell中获取JSON对象的名称字段?

rest - 使用 REST API 的 Azure API 管理的通知列表

string - 用于模式数组的 Powershell 搜索字符串