【问题标题】:check website url status using powershell version 2.0使用 powershell 2.0 版检查网站 url 状态
【发布时间】:2020-11-05 19:47:11
【问题描述】:

我需要使用“PowerShell Version 2.0”检查 URL 是否正常工作 我在互联网上找到了这个脚本,但是对于错误的 URL 来说它并不好。它应该进入else 循环以查找错误的 URL 以及打印网站代码。而且我无法在此脚本中传递凭据。

例如对于www.google.com(正确的URL)状态码应该是200but 对于www.gfjgugy79rt9(Wrong URL) 状态码应该类似于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()

【问题讨论】:

    标签: powershell-2.0


    【解决方案1】:

    在高于 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 中,您只需在要捕获这些异常的范围(函数、脚本)的开头放置一个 Trap 代码:

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

    【讨论】:

    • 嗨,我可以将它用于多个 URL 吗?例如,将所有 URL 放在一个文本文件中并通过 for 循环检索。我尝试了多个 URL,但没有成功。
    • 你可以把这段代码放到一个函数abd循环中调用这个函数。
    猜你喜欢
    • 2017-10-22
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 2016-07-08
    • 2019-07-02
    相关资源
    最近更新 更多