【问题标题】:Handling 404 Errors in PowerShell处理 PowerShell 中的 404 错误
【发布时间】:2019-08-11 04:17:43
【问题描述】:

我有大量博客 URL 需要检查其有效性。我从this answerhere 拼凑了一个脚本。

这是我的脚本:

$siteURL = 'http://example.com/'
$File    = '.\urls.txt'

$NewContent = Get-Content -Path $File | ForEach-Object {
    $_

    $HTTP_Request  = [System.Net.WebRequest]::Create($siteURL + $_)
    $HTTP_Response = $HTTP_Request.GetResponse()
    $HTTP_Status   = [int]$HTTP_Response.StatusCode

    if ($HTTP_Status -eq 200) {
       " - 200"
    } else {
        " - " + $HTTP_Status
    }

    $HTTP_Response.Close()
}

$NewContent | Out-File -FilePath $File -Encoding Default -Force

我的问题是,当它遇到 404 错误时,它不会将其添加到文件中并在控制台中返回以下错误:

Exception calling "GetResponse" with "0" argument(s): "The remote server
returned an error: (404) Not Found."
At C:\Users\user.name\urlcheck.ps1:19 char:9
+         $HTTP_Response = $HTTP_Request.GetResponse()
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : WebException

为什么会出现这个错误?

额外问题:我的“200 - OK”回复被添加到新行,为什么?

【问题讨论】:

    标签: powershell http-status-codes


    【解决方案1】:

    在这一点上,.NET 实现的设计有点糟糕。 WebRequest 不幸抛出错误状态代码。

    根据this 的回答,您可以使用以下解决方法:

    $siteURL = 'http://example.com/'
    $file    = '.\urls.txt'
    
    (Get-Content $file) | foreach {
        $HTTP_Response = $null
        try {
            $HTTP_Request = [System.Net.WebRequest]::Create($siteURL + $_)
            $HTTP_Response = $HTTP_Request.GetResponse()
        }
        catch [System.Net.WebException] {
            # catch this specific exception and get the response from it
            $HTTP_Response = $_.Exception.Response
        }
        catch {
            # for other errors, output the error message:
            "{0} - ERROR: {1}" -f $_, $_.Exception.Message
            continue
        }
        finally {
            # standard handling of IDisposable
            if ($HTTP_Response) { $HTTP_Response.Dispose() }
        }
        $HTTP_Status = $HTTP_Response.StatusCode 
    
        # NOTE: This will also fix your "newline" problem
        "{0} - {1} ({2})" -f $_, [int]$HTTP_Status, $HTTP_Status
    } | Out-File $file -Force
    

    【讨论】:

      【解决方案2】:

      为了处理404 响应(和类似的错误响应),我们需要一些错误处理代码:

      ForEach-Object {
          $_
      
          $HTTP_Request = [System.Net.WebRequest]::Create($siteURL + $_)
      
          try {
              $HTTP_Response = $HTTP_Request.GetResponse()
          }
          catch [System.Net.WebException] {
              # HTTP error, grab response from exception
              $HTTP_Response = $_.Exception.Response
          }
          catch {
              # Something else went horribly wrong, maybe abort?
          }
      
          $HTTP_Status = [int]$HTTP_Response.StatusCode
      
          If ($HTTP_Status -eq 200) {
             " - 200"
          }
          Else {
              " - " + $HTTP_Status
          }
      
          $HTTP_Response.Close()
      }
      

      额外问题:我的 200 -OK 响应被添加到新行,为什么?

      这是因为您在两个单独的语句中输出了 $_" - " + ...。从顶部删除 $_ 并将其全部组合在一个字符串中:

      ForEach-Object {
          $HTTP_Request = [System.Net.WebRequest]::Create($siteURL + $_)
      
          try {
              $HTTP_Response = $HTTP_Request.GetResponse()
          }
          catch [System.Net.WebException] {
              # HTTP error, grab response from exception
              $HTTP_Response = $_.Exception.Response
          }
          catch {
              # Something else went horribly wrong, maybe abort?
          }
          finally {
              # Grab status code and dispose of response stream
              $HTTP_Status = [int]$HTTP_Response.StatusCode
              $HTTP_Response.Dispose()
          }
      
          "$_ - $HTTP_Status"
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-31
        • 2015-04-07
        • 2017-03-02
        • 2013-11-24
        • 1970-01-01
        • 1970-01-01
        • 2016-06-08
        • 2017-11-20
        相关资源
        最近更新 更多