if else based on output of invoke-webrequest in PS

后端 未结 3 445
渐次进展
渐次进展 2020-12-22 07:36

Can someone help me capture only the StatusCode of invoke-webrequest below so that I can determine if a site is up (200) or down (any other code). I think essentially an if

3条回答
  •  半阙折子戏
    2020-12-22 08:08

    Use property dereferencesmember access operator and if to do the work.

    $uri = $args[0]
    
    [Net.ServicePointManager]::SecurityProtocol = ([Net.SecurityProtocolType]::Tls12, [Net.SecurityProtocolType]::Tls11, [Net.SecurityProtocolType]::Tls, [Net.SecurityProtocolType]::Ssl3)
    
    try {
        if ((Invoke-WebRequest $uri -UseBasicParsing -DisableKeepAlive -Method Head).StatusCode -eq 200) {
            Write-Host "The site is up."
        }
        else {
            Write-Host "The site is down."
        }
    }
    catch {
        Write-Host "The site is down."
    }
    

    The script above has been modified, some comments below are obsolete.

提交回复
热议问题