【问题标题】:Do I need both try/catch and -ErrorAction?我需要 try/catch 和 -ErrorAction 吗?
【发布时间】:2015-02-15 05:48:30
【问题描述】:

以下代码尝试以三种不同的方式复制文件test,使用两个具有不同错误管理技术的函数:

  1. 对自己(它应该失败,因为它是不可能的)
  2. 到一个隐藏文件(它应该会失败,因为隐藏文件默认不能被覆盖)
  3. 到一个不存在的文件夹(它应该会失败,因为该文件夹不存在)

两个函数中的一个使用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


    【解决方案1】:

    如果您像这样使用-ErrorAction Stop,您的第一个版本应该可以捕获所有错误:

    function TestTryCatch($N, $Source, $Dest) {
        Write-Output "$N TestTryCatch $Source $Dest"
        try {Copy-Item $Source $Dest -ErrorAction Stop}
        catch {Write-Output "Error: $($error[0].exception.message)"}
    }
    

    这里的关键是 Powershell 区分了终止错误和非终止错误,并且非终止错误不会被 try {} 捕获。使用-ErrorAction Stop 会强制非终止错误停止执行,因此它们会被捕获。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 2014-11-27
      • 1970-01-01
      • 2014-09-17
      • 2020-02-11
      相关资源
      最近更新 更多