通过while循环进行网站检查,并在PowerShell中重新启动服务

时间:2018-12-16 17:23:07

标签: powershell powershell-v4.0

我想做的是一旦网页关闭,重新启动它。服务不会让我们知道它已关闭。 (创作者方面的编程不良),我们仅知道网站关闭后才会关闭。没有警告。没有错误代码,它只是掉下来。我一直在与Invoke-WebRequest合作。

$URL = "http://test.example.org"
while (!(Invoke-WebRequest -Uri $URL -UseBasicParsing -Method Head -ErrorAction SilentlyContinue)) {
    Send-MailMessage -To "admin@example.org" -Body "$URL is down" -Subject "Site Down" -SmtpServer mail.example.org -From "SiteMonitor@Example.org"   
    Get-Service -ComputerName Example_Server -Name "Website Service" | Stop-Service
    sleep 2
    Get-Service -ComputerName Example_Server -Name "Website Service" | Set-Service -Status Running
    sleep 2
    "$(Get-Date)" >> C:\logs\ExampleDown.txt
    if (Invoke-WebRequest -Uri $URL -UseBasicParsing -Method Head -ErrorAction SilentlyContinue) {
        Send-MailMessage -To "admin@example.org" -Body "$URL is Up" -Subject "Site Up" -SmtpServer mail.example.org -From "SiteMonitor@Example.org"   
    }
}

我遇到的唯一问题是,当我在站点关闭时对站点执行Invoke-WebRequest时,它会生成一条错误消息,使脚本每次都无法运行。该错误消息是关于网站无法解析的。我认为while循环将使用布尔值来处理它,并在出现错误消息时执行while循环,因为在if语句中,大多数情况下,错误消息被视为false。

1 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:(无双关语)

try {
  $response = $null
  $LastError = $null
  $response = Invoke-WebRequest -Uri http://localhost -OtherParameters
} catch  {
  $response = $Null
  $LastError = $_
}
if ($null -eq $response -or $null -ne $lastError) { "an error occured" }
else {
  "$($response.Content)"
}
相关问题