Powershell: try/catch/finally cannot catch non-terminating error

来源:互联网 发布:端口数据采集软件 编辑:程序博客网 时间:2024/05/17 12:03


        [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")        try {                $cmd = "Stop-Process -Name abc"                Write-Warning "$cmd"                Invoke-Expression $cmd                Write-Host  -Object "Killed Successfully!!!" -ForegroundColor Green        }        catch {                $msg = $_.Exception.Message;                [System.Windows.Forms.MessageBox]::Show($msg, "Error", [System.Windows.Forms.MessageBoxButtons]::OK);        }



In case abc process does not exist, the catch block does not work because the error is non-terminating error, only terminating error can be caught in Powershell.


Get-Process : Cannot find a process with the name "abc". Verify the process name and call the cmdlet again.
At line:1 char:12
+ Get-Process <<<<  abc
    + CategoryInfo          : ObjectNotFound: (abc:String) [Get-Process], ProcessCommandException
    + FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.GetProcessCommand



we can resovle this issue by setting $ErrorActionPreference to Stop.

$ErrorActionPreference = "Stop"

or 

add -ErrorAction Stop in cmdlet.


Stop-Process -Name abc -ErrorAction Stop


Similarly, Get-Content cmdlet also generate non-terminating error.



http://www.vexasoft.com/blogs/powershell/7255220-powershell-tutorial-try-catch-finally-and-error-handling-in-powershell
0 0