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

Posted

tags:

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

## Powershell Error Handling without Try/Catch

#  Declaring module Paths
$OSDScriptsPath1 = "C:\Windows\System32\WindowsPowerShell\v1.0\Modules\OSDScripts"
$OSDScriptsPath2 = "C:\Program Files\WindowsPowerShell\Modules\OSDScripts"

    #  Removing module using SilentlyContinue parameter and Err variable to store execution errors 
    Remove-Item -Path $OSDScriptsPath1 -Recurse -Force -ErrorAction SilentlyContinue -ErrorVariable +Err
    Remove-Item -Path $OSDScriptsPath2 -Recurse -Force -ErrorAction SilentlyContinue -ErrorVariable +Err

    #  Check if first error does not contain "Cannot find path" write error to console ​
    If ($Err[0] -and $Err[0].Exception -notmatch "Cannot find path"){
        Write-Host "Delete $OSDScriptsPath1 -Failed with Error: $Err[0].Exception"

    #  If no errors occured (except the "Cannot find path") write that the delete operation was succesful
    } Else {
        Write-Host "Delete $OSDScriptsPath1 - Successful!"
    }

    #  Check if second error does not contain "Cannot find path" write error to console ​
    If ($Err[1] -and $Err[1].Exception -notmatch "Cannot find path"){
        Write-Host "Delete $OSDScriptsPath2 -Failed with Error: $Err[1].Exception"

    #  If no errors occured (except the "Cannot find path") write that the delete operation was succesful
    } Else {
        Write-Host "Delete $OSDScriptsPath2 - Successful!"
    }

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

用powershell的try catch, 为啥try里面出现异常,catch 捕获不到呢?

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

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

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

Powershell 如何获取异常的名称

捕获未处理的异常