ChatGPT解决这个技术问题 Extra ChatGPT

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

这可能吗?


P
Panomosh

尝试这样的事情:

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