Exception 捕获一般异常-powershell

Exception 捕获一般异常-powershell,exception,powershell,Exception,Powershell,尝试从$Pingy=Get WmiObject Win32_PingStatus-f“Address='$Fip')捕获常规异常已尝试执行catch[exception]、catch[System.exception]和just catch。使用powershell版本2 问题是如何捕获Get WmiObject的一般异常。代码稍后将检查pingSuccess true或false,以确定如何继续。现在它总是将pingSuccess设置为true,如果抛出异常,我不希望这样 function P

尝试从$Pingy=Get WmiObject Win32_PingStatus-f“Address='$Fip')捕获常规异常已尝试执行catch[exception]、catch[System.exception]和just catch。使用powershell版本2

问题是如何捕获Get WmiObject的一般异常。代码稍后将检查pingSuccess true或false,以确定如何继续。现在它总是将pingSuccess设置为true,如果抛出异常,我不希望这样

function Ping
{   
    param($Fip)
    try
    {
    $Pingy = Get-WmiObject Win32_PingStatus -f "Address='$Fip'"  

    return New-Object PSObject -Property @{
        pingSuccess=$true
        ex=$null
        code=$Pingy.statuscode
        }
    }
    catch [System.Exception]
    {
    return New-Object PSObject -property @{
        ex=$_.Exception
        pingSuccess=$false
        }
#   write-host $exc.gettype()
#   write-host $exc.message
#   write-host $exc.innerException
    }
}
看起来是一样的

Win32_PingStatus -f "Address='somenonsehere'"
不会导致错误。所以你不会得到任何东西,但如果你的目的是检测计算机是否可以ping,也许你可以改变一下你的脚本来做到这一点。 例如:

function Ping
{   
    param($Fip)
    $pingStatus=$false                        
    if ((Get-WmiObject Win32_PingStatus -f "Address='$Fip'").StatusCode -eq 0)   {
            $pingStatus=$true
            #$code=0 ## if you want the code, but you already know that.                        

    } 
         New-Object PSObject -Property @{
            pingSuccess=$pingStatus
          #  code=0
}

}

您好-您能澄清一下您的问题吗?
获取有关返回的帮助。。如果您总是在try中退出函数,则捕获将永远不会执行