-ErrorAction停止后脚本处理不会停止
问题描述:
我正在编写一个脚本,用于写入并调用某些自己的函数。第一个功能我打电话是我记录设置功能,在这里我设置了这样的日志文件:-ErrorAction停止后脚本处理不会停止
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
如果该文件无法创建我想整个下面的脚本处理停止,但所有以下调用仍然处理。事件其他函数调用仍旧执行:(如果日志文件创建失败,我不想要任何东西去为日志文件是强制性的。
答
既然你捕获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)"
答
你需要重新抛出错误..
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