2017-10-06 77 views
1

考虑这个简单的代码:错误行为不停止脚本

Read-Host $path 
try { 
    Get-ChildItem $Path -ErrorAction Continue 
} 

Catch { 
    Write-Error "Path does not exist: $path" -ErrorAction Stop 
    Throw 
} 

Write-Output "Testing" 

为什么是“测试”如果指定了无效的路径将被打印到的壳呢?

脚本不停止在catch块中。我究竟做错了什么?

回答

0

我认为这是你需要的:

$path = Read-Host 'Enter a path' 

try { 
    Get-ChildItem $Path -ErrorAction Stop 
} 
Catch { 
    Throw "Path does not exist: $path" 
} 

Write-Output "Testing" 

根据Sage的回答,您需要在Try块中更改为-ErrorAction Stop。这会强制Get-ChildItem cmdlet发出终止错误,然后触发Catch块。默认情况下(和Continue ErrorAction选项)它会抛出一个无法终止的错误,这些错误不会被try..catch捕获。

如果您希望您的代码在Catch块中停止,请使用Throw和您要返回的消息。这将产生一个终止错误并停止脚本(Write-Error -ErrorAction Stop也将实现终止错误,这只是一个更复杂的方法。通常,当您要返回非终止错误消息时,您应该使用Write-Error)。

1

在您的Try Catch块中,您需要设置Get-ChildItem -ErrorAction Stop ,以便在Catch块中捕获异常。

随着继续,您指示命令不会在发生实际错误时产生终止错误。

编辑: 此外,您的throw语句在那里没有用处,您无需为写入错误指定错误操作。

这是修改后的代码。

$path = Read-Host 

try { 
    Get-ChildItem $Path -ErrorAction stop 
} 

Catch { 
    Write-Error "Path does not exist: $path" 
} 

附加说明

你可以通过设置默认操作应用此默认行为(如果这是你想要的)在整个脚本停止使用:

$ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop