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


127

这是try catchPowerShell 2.0中的

$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());
}

这可能吗?

Answers:


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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.