如何检查重定向的URL后获得PS 200状态码(How to get 200 status code

2019-10-29 06:27发布

我试图得到一个200个状态码的网址,但我不断收到0代替。 该网址运作正常,但问题是它是一个重定向的URL。 即使我尝试最终网址后,重定向它仍然显示我的状态0码。

我怎样才能得到一个网站,是向上或向下正确的状态代码,无论它是否已重定向或不?

这就是我现在的正常工作定期URL的喜欢http://google.com而不是重定向的URL。 不幸的是我正在使用的网址都是私人,但它的格式为http://example.com其在卷起https://example.com/index?redirectUrl=

如果我运行下面的脚本PS:\ CheckUrl.ps1 https://example.com/index?redirectUrl=

...它仍然未能返回200代码的网页来了很好,我是使用1号网址或最终的重定向URL,但状态代码返回0,这意味着它说该网站是下来,这是不正确的。

$url = $args[0]
function Get-WebStatus($url) {
    try {
        [Net.HttpWebRequest] $req = [Net.WebRequest]::Create($url)
        $req.Method = "HEAD"
        [Net.HttpWebResponse] $res = $req.GetResponse()
        if ($res.StatusCode -eq "200") {
            Write-Host "`nThe site $url is UP (Return code: $($res.StatusCode) - $([int] $res.StatusCode))`n"
        } else {
            Write-Host "`nThe site $url is DOWN (Return code: $($res.StatusCode) - $([int] $res.StatusCode))`n"
        }
    } catch {
        Write-Host "`nThe site $url is DOWN (Return code: $($res.StatusCode) - $([int] $res.StatusCode))`n" -ForegroundColor Red -BackgroundColor Black
    }
}
Get-WebStatus $url

Answer 1:

过长的注释。 重要提示: $res = $req.GetResponse()不设置任何值到$res在变量catch的情况下(在$res变量保持不变)。

#url1 = $args[0]
function Get-WebStatus($url) {
    try {
        $req = [System.Net.HttpWebRequest]::Create($url)
        $req.Method    = "HEAD"
        $req.Timeout   = 30000
        $req.KeepAlive = $false
        $res = $req.GetResponse()
        if ($res.StatusCode.value__ -eq 200) {
            Write-Host ("`nThe site $url is UP (Return code: " + 
                "$($res.StatusCode) - " + 
                "$($res.StatusCode.value__))`n") -ForegroundColor Cyan
        } else {
            Write-Host ("`nThe site $url is DOWN (Return code: " +
                "$($res.StatusCode) - " + 
                "$($res.StatusCode.value__))`n") -ForegroundColor Yellow
        }
    } catch {
        $res = $null  ### or ### [System.Net.HttpWebRequest]::new()
        Write-Host ("`nThe site $url is DOWN " + 
            "($($error[0].Exception.InnerException.Message))`n") -Foreground Red
    }
    $res    ### return a value
}
#Get-WebStatus $url1

输出示例:

Get-WebStatus 'https://google.com/index?redirectUrl='
Get-WebStatus 'https://google.com/'
Get-WebStatus 'https://example.com/index?redirectUrl='
 The site https://google.com/index?redirectUrl= is DOWN (The remote server returned an error: (404) Not Found.) The site https://google.com/ is UP (Return code: OK - 200) The site https://example.com/index?redirectUrl= is DOWN (The operation has timed out) 


文章来源: How to get 200 status code in PS after checking a redirected URL