检查重定向的URL后如何在PS中获取200状态代码

时间:2019-02-14 14:57:10

标签: powershell url

我正在尝试获取URL的200状态代码,但我一直在获取0。该url有效,但是问题在于它是重定向的URL。即使我在重定向后尝试使用最终URL,它也仍然显示0状态代码。

无论网站是否被重定向,如何获得正确的状态代码?

这就是我现在所拥有的,它对于像http://google.com这样的常规URL很好,但是对于重定向的URL却不能。不幸的是,我正在使用的网址是私有的,但格式为http://example.com,其结尾为https://example.com/index?redirectUrl=

如果我使用以下命令运行PS脚本:。\ CheckUrl.ps1 https://example.com/index?redirectUrl=

...它仍然无法返回200的代码。无论我使用第一个URL还是最终重定向的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

1 个答案:

答案 0 :(得分:0)

评论太久。重要提示:在$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)