如何区分try catch语句中的Invoke-WebRequest异常(HTTP错误码)

How to differentiate Invoke-WebRequest exception (HTTP error code) in try catch statement

我创建了一个脚本,使用 Invoke-WebRequest cmdlet 使用 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
}

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

Error HTTP 404
Invoke-WebRequest : The remote server returned an error : (404) Not Found.
At line:1 char:1
+ Invoke-WebRequest -Uri https://<censored> -Outfile test.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation : (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Error HTTP 429
Invoke-WebRequest : The remote server returned an error : (429) Too Many Requests.
At line:1 char:1
+ Invoke-WebRequest -Uri "https://<censored> -Outfile test.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation : (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

你可以这样做:

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 
            }
    }
}

由于抛出的是同一个异常,您将无法分别捕获它们。