【发布时间】:2019-08-11 04:17:43
【问题描述】:
我有大量博客 URL 需要检查其有效性。我从this answer 和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 错误时,它不会将其添加到文件中并在控制台中返回以下错误:
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