1

我创建了一个脚本,使用Invoke-WebRequestcmdlet 使用 PowerShell 脚本下载 Internet 上的特定文件。

我有 2 个我想处理的已知异常:404 和 429。

我目前正在使用try/catch声明:

try {
    Invoke-WebRequest -Uri $download_url -OutFile $srr_file
} catch {
    ...snip...
}

但是对于这两个错误,我有相同的代码,这不是我想做的:

try {
    Invoke-WebRequest -Uri $download_url -OutFile $srr_file
} catch [something here] {
    # Here the code I would like to write if the HTTP response is 404 File not found
    # Will certainly be a continue command
} catch [something here] {
    # Here the code I would like to write if the HTTP response is 429 Too many request
    # Will certainly be a sleep command for 1 hour
}

这里是两种情况下命令的输出:

错误 HTTP 404
Invoke-WebRequest:远程服务器返回错误:(404)未找到。
在行:1 字符:1
+ Invoke-WebRequest -Uri https://<censored> -Outfile test.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation : (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId:WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

错误 HTTP 429
Invoke-WebRequest:远程服务器返回错误:(429) Too Many Requests。
在行:1 字符:1
+ Invoke-WebRequest -Uri "https://<censored> -Outfile test.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation : (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId:WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
4

1 回答 1

2

你可以这样做:

try 
{
    $response = Invoke-WebRequest -Uri $download_url -OutFile $srr_file
} 
catch 
{
    switch ($_.Exception.Response.StatusCode.Value__)
    {
        404 { 
            // Here´s the code I would like to write if the HTTP response is 404 File not found
            // Will certainly be a continue command            
            }
        429 {
            // Here´s the code I would like to write if the HTTP response is 429 Too many request
            // Will certainly be a sleep command for 1 hour 
            }
    }
}

由于抛出相同的异常,您将无法单独捕获它们。

于 2019-10-09T10:17:40.343 回答