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

Med*_*edo 127 powershell try-catch

这是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")
    }  
}
Run Code Online (Sandbox Code Playgroud)

但我想要做的就是在c#中

catch( WebException ex)
{
    Log(ex.ToString());
}
Run Code Online (Sandbox Code Playgroud)

这可能吗?

ste*_*tej 183

尝试这样的事情:

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

例外是在$_变量中.你可能会这样探索$_:

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

我想它会为您提供所需的所有信息.

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