powershell 2.0 try catch 如何访问异常 [英] powershell 2.0 try catch how to access the exception

查看:51
本文介绍了powershell 2.0 try catch 如何访问异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是 PowerShell 2.0 中的 try catch

This is the try catch in PowerShell 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#

but what I want to do is something like in c#

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

这可能吗?

推荐答案

试试这个:

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

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

The exception is in the $_ variable. You might explore $_ like this:

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

我认为它会给你所有你需要的信息.

I think it will give you all the info you need.

我的规则:如果有一些数据没有显示出来,尽量使用-force.

My rule: if there is some data that is not displayed, try to use -force.

这篇关于powershell 2.0 try catch 如何访问异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆