powershell 使用Try / Catch进行Powershell错误处理

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了powershell 使用Try / Catch进行Powershell错误处理相关的知识,希望对你有一定的参考价值。

## Powershell Error Handling with Try/Catch
​
#  Declaring module Paths
$OSDScriptsPath1 = "C:\Windows\System32\WindowsPowerShell\v1.0\Modules\OSDScripts"
$OSDScriptsPath2 = "C:\Program Files\WindowsPowerShell\Modules\OSDScripts"
​
#  Removing module using -ErrorAction Stop parameter and Err variable to store execution errors
#  We use -ErrorAction Stop in order to treat all errors as Terminating Errors
Try {
    Remove-Item -Path $OSDScriptsPath1 -Recurse -Force -ErrorAction Stop -ErrorVariable +Err
    Write-Host "Delete $OSDScriptsPath1 - Successful!"
}

#  Catch Item Not Found Exception error
Catch [System.Management.Automation.ItemNotFoundException]
{
    Write-Host "$OSDScriptsPath1 - Not Found!" -ForegroundColor Green
}

#  Catch all other errors
Catch {
    Write-Host "Delete $OSDScriptsPath1 - Failed!"
    Write-Host "Failed with Error: "$Err
}

#  Removing module using -ErrorAction Stop parameter and Err variable to store execution errors
#  We use -ErrorAction Stop in order to treat all errors as Terminating Errors
Try {
    Remove-Item -Path $OSDScriptsPath2 -Recurse -Force -ErrorAction Stop -ErrorVariable +Err
    Write-Host "Delete $OSDScriptsPath2 - Successful!"
}

#  Catch Item Not Found Exception error
Catch [System.Management.Automation.ItemNotFoundException]
{
    Write-Host "$OSDScriptsPath2 - Not Found!" -ForegroundColor Green
}

#  Catch all other errors
Catch {
    Write-Host "Delete $OSDScriptsPath2 - Failed!"
    Write-Host "Failed with Error: "$Err
}
​

以上是关于powershell 使用Try / Catch进行Powershell错误处理的主要内容,如果未能解决你的问题,请参考以下文章

powershell 使用多个命令或变量使用Try / Catch进行Powershell错误处理

powershell 没有Try / Catch的Powershell错误处理

Powershell错误处理,try catch finally

Powershell Try/Catch 或 If/Else 不适用于我的脚本

Powershell 如何获取异常的名称

捕获未处理的异常