URL监视的Powershell脚本

时间:2019-12-03 03:47:38

标签: powershell

我已经开发了一个Powershell脚本,该脚本可以连续监视URL,并在URL向上/向下时触发邮件。但是,它不会在它触发的邮件中显示该URL。

代码:

   Add-Type -AssemblyName System.Web Add-Type -AssemblyName System.Web.Extensions

  function Send-Mail([string] $url, [switch] $serverDown) {


$PSEmailServer    = ""
$smtpPort         = "25" 
$mailFrom         = "sender@my.mailserver.com"
$mailTo           = "recepient@mail.com"
$messageSubject   = "Web monitoring notification"

if( $serverdown.IsPresent ) {

    $body = @"
        <p>Hello,</p>
        <p>Server $($url) is reported down at $(Get-Date)</p>
"@
}
else {

$body = @"
        <p>Hello,</p>
        <p>Server $($url) is reported up again at $(Get-Date)</p>
 "@
  }

Send-MailMessage -SmtpServer $PSEmailServer -From $mailFrom -To $mailTo -Subject $messageSubject -Body $body -BodyAsHtml -Port $smtpPort 
  }

     # ---------------- MAIN ------


 $url            = 
 "https://www.google.com"
  $errFlag        = $false
 $formerErrFlag  = $false
 $requestSeconds = 60

  while( $true ) {

try {
    $result        = Invoke-Webrequest -Uri $url -Method GET 
    $errFlag       = $false
}
catch [System.Net.WebException] {                              # e. g. error 500
    $responseBody = $_.Exception
    $errorDetails = ''
    $errFlag      = $true
}
catch {
    $result = $_.Exception.Response.GetResponseStream()
    $reader = New-Object System.IO.StreamReader($result)
    $reader.BaseStream.Position = 0
    [void]$reader.DiscardBufferedData()
    $responseBody = $reader.ReadToEnd()
    $errorDetails = $_.ErrorDetails.Message
    $errFlag      = $true
}


Send-Mail -url $url -serverDown:$errFlag

$formerErrFlag = $errFlag

Start-Sleep -Seconds $requestSeconds          # wait till next request
  }

输出:您好, 服务器在12/03/2019 03:34:30再次报告了

预期输出:您好, 网址(https://www.google.com)在12/03/2019 03:34:30再次报告

几个问题:

  1. 该代码仅用于“其他”部分,不检查“ if”条件。

  2. 是否可以在同一脚本中调用多个URL。

0 个答案:

没有答案