Powershell Script to monitoring status and send email results

前端 未结 1 552
时光取名叫无心
时光取名叫无心 2021-01-14 09:44

I have a lot of websites to monitor their up/down status, possible errors, ping and the other things that I managed to get with a script. My idea is the following: This scri

相关标签:
1条回答
  • 2021-01-14 10:35

    Since you're using Powershell v3, you should be using Send-MailMessage instead of dealing with System.Net.

    $URLListFile = "C:\URLList.txt"  
    $URLList = Get-Content $URLListFile -ErrorAction SilentlyContinue 
      $Result = @() 
    
    
      Foreach($Uri in $URLList) { 
      $time = try{ 
      $request = $null 
    
      $result1 = Measure-Command { $request = Invoke-WebRequest -Uri $uri } 
      $result1.TotalMilliSeconds 
      }  
      catch 
      { 
    
       $request = $_.Exception.Response 
       $time = -1 
      }   
      $result += [PSCustomObject] @{ 
      Time = Get-Date; 
      Uri = $uri; 
      StatusCode = [int] $request.StatusCode; 
      StatusDescription = $request.StatusDescription; 
      ResponseLength = $request.RawContentLength; 
      TimeTaken =  $time;  
      } 
    
    } 
    
    if($result -ne $null) 
    { 
        $Outputreport = "<HTML><TITLE>Website Report Status</TITLE><BODY background-color:peachpuff><font color =""#99000"" face=""Microsoft Tai le""><H2> Website Report Status </H2></font><Table border=1 cellpadding=0 cellspacing=0><TR bgcolor=gray align=center><TD><B>URL</B></TD><TD><B> Code </B></TD><TD><B> Status </B></TD><TD><B> Duration </B></TD><TD><B> MS (Ping) </B></TD</TR>" 
        Foreach($Entry in $Result) 
        { 
            if($Entry.StatusCode -ne "200") 
            { 
               $Outputreport += "<TR bgcolor=red>" 
            } 
            else 
            { 
                $Outputreport += "<TR>" 
            } 
            $Outputreport += "<TD>$($Entry.uri)</TD><TD align=center>$($Entry.StatusCode)</TD><TD align=center>$($Entry.StatusDescription)</TD><TD align=center>$($Entry.ResponseLength)</TD><TD align=center>$($Entry.timetaken)</TD></TR>" 
        } 
        $Outputreport += "</Table></BODY></HTML>" 
    } 
    
    $Outputreport | out-file C:\URLReport.htm 
    Invoke-Item C:\URLReport.htm   
    
    $EmailFrom = "noreply@domain.com"
    $EmailTo = "destinyemail@domain.com"
    $EmailSubject = "URL Report"
    $emailbody = " body message "
    $SMTPServer = "smtpserver.company.com"
    
    $emailattachment = "C:\URLReport.htm"
    
    Send-MailMessage -Port 587 -SmtpServer $SMTPServer -From $EmailFrom -To $EmailTo -Attachments $emailattachment -Subject $EmailSubject -Body $emailbody -Bodyashtml;
    
    0 讨论(0)
提交回复
热议问题