相关疑难解决方法(0)

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

这是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)

这可能吗?

powershell try-catch

127
推荐指数
1
解决办法
10万
查看次数

PowerShell:创建自定义异常

这是我的代码:

Function Foo {
    If (1 -Eq 2) {
        # Do stuff
    }
    Else {
        # Throw custom exception
    }
}

Try {
    Foo

    Write-Host "Success"
}
Catch {
    $ErrorMessage = $_.Exception.InnerException.Message

    Write-Host "Failure"

    # Do stuff with the error message
}
Run Code Online (Sandbox Code Playgroud)

我想替换# Throw custom exception会导致Catch触发的代码.我怎样才能做到这一点?

.net powershell

7
推荐指数
1
解决办法
1万
查看次数

在 powershell 中抛出多个自定义异常

我有一种情况,我必须在我的 powershell 脚本的 try 块中抛出多个自定义异常,如下所示

try {
    if (!$condition1) {
        throw [MyCustomException1] "Error1"
    }
    if (!$condition2) {
        throw [MyCustomException2] "Error2"
    }
}catch [MyCustomException1] {
    #do some business logic
}catch [MyCustomException2] {
    #do some other business logic
}catch{
    #do something else
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在不编写 .net 类MyCustomException1MyCustomException2. 我不必在类中存储任何信息,但我只需要一种区分异常的方法。我可以做如下,但我只是想知道是否有更清洁的东西。

try {
    if (!$condition1) {
        throw "Error1"
    }
    if (!$condition2) {
        throw "Error2"
    }
}catch {
    if($_.tostring() -eq "Error1"){
        Write-Host "first exception"
    }elseif($_.tostring() -eq "Error2"){
        Write-Host "Second exception"
    }else {
        Write-Host …
Run Code Online (Sandbox Code Playgroud)

powershell exception-handling

2
推荐指数
1
解决办法
5463
查看次数

标签 统计

powershell ×3

.net ×1

exception-handling ×1

try-catch ×1