在 PowerShell 中处理 404 错误

Handling 404 Errors in PowerShell

我有一大堆博客 URL 需要检查其有效性。我从 this answer and from here.

中整理了一个脚本

这是我的脚本:

$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 错误时,它不会将此添加到文件中,并且 returns 控制台中出现以下错误:

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”回复被添加到一个新行,为什么?

此时 .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

为了处理 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()
}

Bonus question: my 200 -OK responses are getting added to a new line, why?

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

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