【发布时间】:2020-08-10 02:49:38
【问题描述】:
我正在尝试修改下面的代码,以便它可以在主网页下测试网站页面:
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
最后,当网页无法访问或主机无法访问时,如何过滤掉错误信息?所以错误可以更友好,例如:
- 找不到网址
- 无法访问主机。
【问题讨论】:
-
您可能需要使用 URI 的主机+域部分。
($url -split '/')[0]应该可以工作 -
@AdminOfThings,感谢您对代码的建议,但是,当我将其修改为: $web = Invoke-WebRequest -Uri https://($url -split '/')[ 0] -Method Head -UseDefaultCredentials -UseBasicParsing -ErrorAction Stop 它不适用于所有服务器地址和 URL 输入?
-
仅对 dns 解析部分执行此操作。
标签: powershell