我目前在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
}
我可以在日志文件中添加项目,因此我知道这不是文件的权限问题。我错过了什么?
答案 0 :(得分:3)
我相信你得到的错误是无法终止的。这就是为什么它不会在一个捕获块中结束。
尝试使用此代替您的复制项目行:
Copy-Item $scriptPath\Devcon.exe C:\Windows\System32 -ErrorAction Stop