【发布时间】:2015-02-15 05:48:30
【问题描述】:
以下代码尝试以三种不同的方式复制文件test,使用两个具有不同错误管理技术的函数:
- 对自己(它应该失败,因为它是不可能的)
- 到一个隐藏文件(它应该会失败,因为隐藏文件默认不能被覆盖)
- 到一个不存在的文件夹(它应该会失败,因为该文件夹不存在)
两个函数中的一个使用try/catch 管理错误并能够检测前两个错误,另一个使用-ErrorAction 并能够检测第三个错误。
是否有一种技术可以捕获所有错误?
还是我总是需要同时使用这两种技术?
function TestTryCatch($N, $Source, $Dest) {
Write-Output "$N TestTryCatch $Source $Dest"
try {Copy-Item $Source $Dest}
catch {Write-Output "Error: $($error[0].exception.message)"}
}
function TestErrorAction($N, $Source, $Dest) {
Write-Output "$N TestErrorAction $Source $Dest"
Copy-Item $Source $Dest -ErrorAction SilentlyContinue
if(!$?) {Write-Output "Error: $($error[0].exception.message)"}
}
New-Item 'test' -ItemType File | Out-Null
(New-Item 'hidden' -ItemType File).Attributes = 'Hidden'
TestTryCatch 1 'test' 'test'
TestTryCatch 2 'test' 'hidden'
TestTryCatch 3 'test' 'nonexistingfolder\test'
TestErrorAction 1 'test' 'test'
TestErrorAction 2 'test' 'hidden'
TestErrorAction 3 'test' 'nonexistingfolder\test'
Remove-Item 'test'
Remove-Item 'hidden' -Force
【问题讨论】:
标签: powershell error-handling try-catch