在-ErrorAction停止后,脚本处理不会停止

时间:2016-07-29 12:53:05

标签: windows powershell error-handling

我正在编写一个脚本,我已经编写并调用了一些自己的函数。我调用的第一个函数是我的日志记录设置函数,我在其中设置了这样的日志文件:

function Create-Logfile {
    if (!(Test-Path $Path)) { 

        try {
            Write-Verbose "Write-Log: Creating $Path" 
            $NewLogFile = New-Item $Path -Force -ItemType File -ErrorAction stop
        } catch {
            Write-Verbose "Write-Log: Creating $Path failed: $($error[0].Exception.Message)" 
        }

    } 

    write-host 'i do still execute'
}

function Do-Something{
    write-host 'doing something'
}

Create-LogFile #create the file
write-host 'processing didnt stop'
Do-Something

如果无法创建文件,我希望停止以下整个脚本处理,但仍会处理所有后续调用。事件其他函数调用仍然执行:(如果日志文件创建失败,我不希望任何事情继续,因为日志文件是强制性的。

2 个答案:

答案 0 :(得分:1)

您需要重新抛出错误..

function Create-Logfile {
    if (!(Test-Path $Path)) { 

        try {
            Write-Verbose "Write-Log: Creating $Path" 
            $NewLogFile = New-Item $Path -Force -ItemType File -ErrorAction stop
        } catch {
            Write-Verbose "Write-Log: Creating $Path failed: $($error[0].Exception.Message)" 
           Throw
        }

    } 

    write-host 'i do still execute'
}

function Do-Something{
    write-host 'doing something'
}

Create-LogFile #create the file
write-host 'processing didnt stop'
Do-Something

答案 1 :(得分:1)

由于您正在捕获try catch块中的终止错误,因此您必须在write-host命令之后添加终止语句。有几种可供选择,具体取决于您的需求(例如,退出,休息等)。

示例:

try 
{
  Write-Verbose "Write-Log: Creating $Path" 
  $NewLogFile = New-Item $Path -Force -ItemType File -ErrorAction stop
} 
catch 
{
  Write-Verbose "Write-Log: Creating $Path failed: $($error[0].Exception.Message)"
  exit
}

或者,您可以抛出自己的终止错误:

throw "Write-Log: Creating $Path failed: $($error[0].Exception.Message)"