powershell 2.0尝试捕获如何访问异常

时间:2010-02-02 08:23:01

标签: powershell try-catch

这是PowerShell 2.0中的try catch

$urls = "http://www.google.com", "http://none.greenjump.nl", "http://www.nu.nl"
$wc = New-Object System.Net.WebClient 

foreach($url in $urls)
{
    try
    {
        $url
        $result=$wc.DownloadString($url)
    }
    catch [System.Net.WebException]
    {
        [void]$fails.Add("url webfailed $url")
    }  
}

但我想要做的就像在c#

catch( WebException ex)
{
    Log(ex.ToString());
}

这可能吗?

1 个答案:

答案 0 :(得分:183)

尝试这样的事情:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    Write-Host $_.Exception.ToString()
}

例外在$_变量中。您可以像这样探索$_

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    $_ | fl * -Force
}

我认为它会为您提供所需的所有信息。

我的规则:如果有一些数据未显示,请尝试使用-force