powershell - 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
最后,当网页无法访问或主机无法访问时,如何过滤掉错误消息?所以错误可以更友好,例如:
- 找不到网址
- 无法访问主机。
解决方案
该[System.Net.Dns]::GetHostAddresses
方法需要一个主机名或 IP 地址作为参数。在参数中包含 URL 将引发错误。与您的数据集产生一致结果的一种简单方法是从 URL 中拆分主机名和域:
Write-Host "`nURL: $(($URL -split '/')[0]) - $([System.Net.Dns]::GetHostAddresses(($URL -split '/')[0]))"
推荐阅读
- ruby-on-rails - Rails Bootstrap 4,按下浏览器上的后退按钮后下拉菜单停止工作
- php - 如何增加 json_encode 深度限制
- android - Android 上的 Fastlane 框架截图
- google-cloud-firestore - 设置或更新行为类似于数组的子集合
- c# - 使用 Azure Blob 存储对付费媒体文件进行安全媒体共享
- pandas - Pandas - 按多个条件过滤重复记录
- python - Django:父对象没有属性children_set
- javascript - javascript 从平面 json 数组(数据结构)构建类别树
- javascript - 基于正则表达式组的Typescript中从后面出现的数字拆分字符串
- typescript - 如何正确缩小“未知”类型