首页 > 解决方案 > Powershell 测试网站页面可用性和 HTTP 响应代码状态 try/catch

问题描述

我正在尝试修改下面的代码,以便它可以测试主网页下的网站页面:

Clear-Host
$serverName = 'hotel.com/login', 'bing.com/help', 'yahoo.com/mail', 'bong.com', 'bing.com', 'hotel.com'
$statusCodesAllowed = (200, 302, 401) #Update this array to include the HTTP status codes that you want to mark as OK.$stat = 0

Foreach ($URL in $serverName) {
    Try {
        $web = Invoke-WebRequest -Uri https://$URL -Method Head -UseDefaultCredentials -UseBasicParsing -ErrorAction Stop
        $stat = [int]($statusCodesAllowed -contains $web.statusCode)
        Write-Host "`nURL: $($URL) - $([System.Net.Dns]::GetHostAddresses($URL))" -ForegroundColor Yellow
        Write-Host 'Statistic.Status: '$stat -ForegroundColor Green
        Write-Host 'Message.Status: ' $web.StatusCode $web.StatusDescription -ForegroundColor Green
    }

    Catch {
        $statusCode = ($_.Exception.Message.Substring(($_.Exception.Message.IndexOf('(') + 1), 3))
        $stat = [int]($statusCodesAllowed -contains $statusCode)
        Write-Host "`nURL: $($URL) - $([System.Net.Dns]::GetHostAddresses($URL))" -ForegroundColor Red
        Write-Warning 'Statistic.Status: '$stat
        Write-Warning 'Message.Status: '$_.Exception.Message
    }
}

Finally { Remove-Variable serverName, statusCodesAllowed, stat, web, statusCode -ErrorAction SilentlyContinue }

上面的代码适用于主页,但不适用于进一步的main.website/pagename格式。

错误:

Exception calling "GetHostAddresses" with "1" argument(s): "No such host is known"
At line:17 char:40
+ ...  "`nURL: $($URL) - $([System.Net.Dns]::GetHostAddresses($URL))" -Fore ...
+                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SocketException
 
Exception calling "GetHostAddresses" with "1" argument(s): "No such host is known"
At line:17 char:40
+ ...  "`nURL: $($URL) - $([System.Net.Dns]::GetHostAddresses($URL))" -Fore ...
+                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SocketException
 
Exception calling "GetHostAddresses" with "1" argument(s): "No such host is known"
At line:17 char:40
+ ...  "`nURL: $($URL) - $([System.Net.Dns]::GetHostAddresses($URL))" -Fore ...
+                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SocketException

最后,当网页无法访问或主机无法访问时,如何过滤掉错误消息?所以错误可以更友好,例如:

  1. 找不到网址
  2. 无法访问主机。

标签: powershell

解决方案


[System.Net.Dns]::GetHostAddresses方法需要一个主机名或 IP 地址作为参数。在参数中包含 URL 将引发错误。与您的数据集产生一致结果的一种简单方法是从 URL 中拆分主机名和域:

Write-Host "`nURL: $(($URL -split '/')[0]) - $([System.Net.Dns]::GetHostAddresses(($URL -split '/')[0]))"

推荐阅读