【发布时间】:2019-12-08 04:07:30
【问题描述】:
我需要一种方法来从 PS 脚本中确定任何网页是打开还是关闭,无论它是否首先提示输入凭据。即使页面需要安装 java 或其他任何原因。这里的目标是确定页面是否存在,它是否正常工作或是否可以显示都无关紧要。毕竟,它应该只是告诉我在使用 .\sitecheck.ps1 'https://trac.edgewall.org/login' 执行脚本后站点/页面是 UP 还是 DOWN
如果我们可以打印页面关闭的原因(例如当您收到 401 错误时)并打印错误消息和状态代码(整数),那就太好了。
我正在尝试解决这个显然无法正常工作的脚本,因为我正在尝试寻找解决方案:
# First we create the request.
$url = $args[0]
$HTTP_Request = [System.Net.WebRequest]::Create($url)
# We then get a response from the site.
$HTTP_Response = $HTTP_Request.GetResponse()
# We then get the HTTP code as an integer.
$HTTP_Status = [int]$HTTP_Response.StatusCode
If ($HTTP_Status -eq 200) {
Write-Host "Site is OK!"
}
Else {
Write-Host "The Site may be down, please check!"
}
# Finally, we clean up the http request by closing it.
If ($HTTP_Response -eq $null) { } Else { $HTTP_Response.Close()}
有人在此网站上回答了类似问题:
"如果 URL 需要凭据,您需要添加 $HTTP_Request.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials。您需要在 $HTTP_Response = $HTTP_Request.GetResponse() 行周围添加 Try..Catch,如果失败, $HTTP_Response 将为空,因此无法关闭,因为它已经为空 - 就像当您收到 (404) Not Found 时,您将没有响应并且错误将是您无法在 null 上调用方法-valued 表达式,如果您尝试对其执行 .Close()。"
不幸的是,我不知道该怎么做。目前我收到以下错误。大多数实际错误消息都是准确的,因为我没有输入正确的凭据,因此出现 401 错误代码:
使用“0”参数调用“GetResponse”的异常:“远程 服务器返回错误:(401)未经授权。”在 C:\Users\test\sitecheck.ps1:11 char:1 + $HTTP_Response = $HTTP_Request.GetResponse() + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : WebException
【问题讨论】:
-
登录后您只会收到200。如果您还没有登录,不要指望 200。但是您可以检查svn.edgewall.com 是否已启动。我相信是提供登录的服务
标签: powershell