powershell中的错误捕获机制

Error catching mechanism in powershell

这里只是一个宽泛的问题 - powershell 中是否有通用的错误捕获机制?我遇到问题,通过 powershell 脚本连接到 MSSSQL 服务器随机超时,然后重新 运行 就没问题了。

只是想知道在powershell 中是否有可用的try-catch 或类似的错误捕获。或者,如果有人有更好的解决连接超时的方法,请告诉我。

谢谢。 祖尔菲卡尔

是的,您可以使用 Try-Catch 块。 这是一个例子:

Write-Host "Disabling IP v6 - Reboot required after installation/update!" 
$breboot = $True
try
{
    New-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters\" -Name "DisabledComponents" -Value 0xffffffff -PropertyType "DWord" -ErrorAction Stop
}
catch
{
    Write-Host ("IPv6 already disabled - no reboot required!")
    $breboot = $False
}

我推荐 kevin marquette 的博文: https://kevinmarquette.github.io/2017-04-10-Powershell-exceptions-everything-you-ever-wanted-to-know/.