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