PowerShell 2.0 and how to handle exceptions?

后端 未结 1 1195
孤城傲影
孤城傲影 2021-02-06 07:39

Why I get error message printed on the console when running these two simple samples ? I want that I get \"Error testing :)\" printed on the console insted of:

1条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-06 08:29

    First example

    The error happens at compile/parsing time (PowerShell is clever enough), so that the code is not even executed and it cannot catch anything, indeed. Try this code instead and you will catch an exception:

    try
    {
        $x = 0
        $i = 1/$x
        Write-Host $i
    }
    catch [Exception]
    {
        Write-Host "Error testing :)"
    }
    

    Second example

    If you set $ErrorActionPreference = 'Stop' globally then you will get "Error testing :)" printed, as expected. But your $ErrorActionPreference is presumably 'Continue': in that case there is no terminating error/exception and you just get the non terminating error message printed to the host by the engine.

    Instead of the global $ErrorActionPreference option you can also play with Get-WmiObject parameter ErrorAction. Try to set it to Stop and you will catch an exception.

    try
    {
        Get-WmiObject -ErrorAction Stop -ComputerName possibly.nonexisting.domain.com -Credential (Get-Credential) -Class Win32_logicaldisk
    }
    catch [Exception]
    {
        Write-Host "Error testing :)"
    }
    

    0 讨论(0)
提交回复
热议问题