使用powershell 2.0版检查网站网址状态

时间:2017-01-23 04:13:36

标签: powershell-v2.0

我需要使用“PowerShell版本2.0”检查URL是否正常工作 我通过互联网找到了这个脚本,但对于错误的URL,它并没有得到满足。它应该在else循环中输入错误的URL以及打印网站代码。而且我无法在此脚本中传递凭据。

e.g。对于www.google.com(正确的网址),状态代码应为200但是 对于www.gfjgugy79rt9(错误的网址)状态代码应该类似于404

我在互联网上找到PowerShell版本2.0的脚本:

# First we create the request.
$HTTP_Request = [System.Net.WebRequest]::Create('http://google.com')

# 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.
$HTTP_Response.Close()

1 个答案:

答案 0 :(得分:0)

在高于2.0的PowerShell中,您应该使用try ... catch ... finally,因为当URI不符合或者DNS无法解决地址部分时,此代码会触发异常:

try {
  # First we create the request.
  $HTTP_Request = [System.Net.WebRequest]::Create('http://google.com')

  # 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!"
  }
}
catch {
  Write-Verbose $_.ScriptStackTrace
  Write-Verbose "Ligne $($_.InvocationInfo.ScriptLineNumber) : $($_.exception.message)"
}
finally {
  # Finally, we clean up the http request by closing it.
  $HTTP_Response.Close()
}

在PowShell 2.0中,您只需要在范围(函数,脚本)的beginnig中放置Trap代码,以便捕获这些异常:

trap
{
  Write-Verbose $_.ScriptStackTrace
  Write-Verbose "Ligne $($_.InvocationInfo.ScriptLineNumber) : $($_.exception.message)"
  Write-Verbose ([datetime]::Now)
  return
}