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 script will run with task scheduler, get the results and send us (from the SQA publications) an email. So, I managed to create the script with success, he gets all I need and generates a html file in the C: drive. My problem is that after I get the result the function which sends the email isn't sending the email. I don't get any error messages, debug is fine, SMTP and all configurations are correct. But it won't send the email with the html file attached!
The code is this:
$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-Expression 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"
function send_email {
$mailmessage = New-Object system.net.mail.mailmessage
$mailmessage.from = ($emailfrom)
$mailmessage.To.add($emailto)
$mailmessage.Subject = $emailsubject
$mailmessage.Body = $emailbody
$attachment = New-Object System.Net.Mail.Attachment($emailattachment, 'html')
$mailmessage.Attachments.Add($attachment)
$mailmessage.IsBodyHTML = $true
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.Send($mailmessage)
}
EDIT4: > ($SmtpServer, 587) Beeing " 587 " the port that our smtp server uses.
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;
Related
I have the following PowerShell Script, found and modified some time ago, however after checking and testing it in the past, I put this project away and wanted to check again now. However, the script should check a given website and tell how long it took to reach etc, but when I want to check with an internal website it is not working and constantly showing the cells with red color and error 200, however, external website like google or Facebook are measurable by the script.
Here is the script:
$URLListFile = "C:\Users\***\Desktop\websites.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 Availability Report</TITLE><BODY background-color:peachpuff><font color =""#99000"" face=""Microsoft Tai le""><H2> Website Availability Report </H2></font><Table border=1 cellpadding=0 cellspacing=0><TR bgcolor=gray align=center><TD><B>URL</B></TD><TD><B>StatusCode</B></TD><TD><B>StatusDescription</B></TD><TD><B>ResponseLength</B></TD><TD><B>TimeTaken</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:\Users\***\Desktop\Test.htm
Invoke-Expression C:\Users\***\Desktop\Test.htm
Also attaching the picture about the result. Would you be able to help me why internal websites can not be measured, how should this script be modified so it can work? Website Availability Report
error
Okay, so adding this line solved my issue, as the webpage is not accepting SSL 1.0 but 1.2 only connection. [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12;
I created the following script to check the website status and the IIS instance status. When I manually runs it from PowerShell ISE with Adminstrator, it works fine but when I triggered from Task Scheduler, it just didn’t worked! And it was due to GET-WEBSITESTATE as this cmdlet required to run from PS ISE Administrator.
My question, what is the command need to setup in Task Scheduler?
Currently, i setup the task schedule with the following:
Program/Script: Powershell.exe
Add arguments: powershell -executionpolicy bypass -file "D:\PS\CheckPMRWebpage\Code\Monitor PMR webpage 6-1.ps1
## The URI list to test
$URLListFile = "D:\PS\CheckPavcapWebpage\Code\PavCapurlList.DAT"
$URLList = Get-Content $URLListFile -ErrorAction SilentlyContinue
$Result = #()
Foreach($Uri in $URLList) {
$time = try{
$request = $null
## Request the URI, and measure how long the response took.
$result1 = Measure-Command { $request = Invoke-WebRequest -Uri $uri }
$result1.TotalMilliseconds
}
catch
{
<# If the request generated an exception (i.e.: 500 server
error or 404 not found), we can pull the status code from the
Exception.Response property #>
$request = $_.Exception.Response
$time = -1
}
# $lStatusCode = [int] $request.StatusCode
# if ($lStatusCode -eq 401){
# $linfo = "The site is ok."
# }
$result += [PSCustomObject] #{
Time = Get-Date;
Uri = $uri;
StatusCode = [int] $request.StatusCode;
StatusDescription = $request.StatusDescription;
ResponseLength = $request.RawContentLength;
TimeTaken = $time;
}
}
##################################################
#Prepare body in HTML format for URL
##################################################
if($result -ne $null)
{
$Outputreport = "<HTML><TITLE>PMR Website Availability Report</TITLE><BODY background-color:peachpuff><font color =""#99000"" face=""Microsoft Tai le""><H2> PavCap Website Availability Report </H2></font><Table border=1 cellpadding=0 cellspacing=0><TR bgcolor=gray align=center><TD><B>URL</B></TD><TD><B>StatusCode</B></TD><TD><B>StatusDescription</B></TD><TD><B>Additional Info</B></TD><TD><B>ResponseLength</B></TD><TD><B>TimeTaken</B></TD></TR>"
Foreach($Entry in $Result)
{
if($Entry.StatusCode -eq "200")
{
$Outputreport += "<TR bgcolor=lightgreen>"
$Outputreport += "<TD>$($Entry.uri)</TD><TD align=center>$($Entry.StatusCode)</TD><TD align=center>$($Entry.StatusDescription)</TD><TD align=center></TD><TD align=center>$($Entry.ResponseLength)</TD><TD align=center>$($Entry.timetaken)</TD></TR>"
}
elseif($Entry.StatusCode -eq "401")
{
$Outputreport += "<TR bgcolor=yellow>" #<TD></TD><TD align=center></TD><TD align=center></TD><TD align=center>$($Entry.AddInfo)</TD><TD align=center></TD><TD align=center></TD></TR>"
$Outputreport += "<TD>$($Entry.uri)</TD><TD align=center>$($Entry.StatusCode)</TD><TD align=center>$($Entry.StatusDescription)</TD><TD align=center>Website is up but it failed on Authentication!</TD><TD align=center>$($Entry.ResponseLength)</TD><TD align=center>$($Entry.timetaken)</TD></TR>"
#AddInfo = "Site is ok as it failed on Authentication"
}
else
{
$Outputreport += "<TR bgcolor=red>"
$Outputreport += "<TD>$($Entry.uri)</TD><TD align=center>$($Entry.StatusCode)</TD><TD align=center>$($Entry.StatusDescription)</TD><TD align=center>Website is not up - please check!</TD><TD align=center>$($Entry.ResponseLength)</TD><TD align=center>$($Entry.timetaken)</TD></TR>"
#AddInfo = "red"
}
#$Outputreport += "<TD>$($Entry.uri)</TD><TD align=center>$($Entry.StatusCode)</TD><TD align=center>$($Entry.StatusDescription)</TD><TD align=center>$($Entry.AddInfo)</TD><TD align=center>$($Entry.ResponseLength)</TD><TD align=center>$($Entry.timetaken)</TD></TR>"
}
$Outputreport += "</Table></BODY></HTML>"
}
$Outputreport | out-file D:\PS\CheckPavcapWebpage\siteavailabilityrpt.html
#Invoke-Expression D:\PS\CheckWebpage_and_IIS\siteavailabilityrpt.html
######################################
# The Instances Name list to check
######################################
$InsNameFile = "D:\PS\CheckPavcapWebpage\Code\PavCapInsName.dat"
$InsList = Get-Content $InsNameFile -ErrorAction SilentlyContinue
$Result1 = #()
Foreach($Ins in $InsList){
$InsNameState = (Get-WebsiteState -Name $Ins).value
$result1 += [PSCustomObject] #{
#Time = Get-Date;
InsName = $ins;
InsStatus = $InsNameState;
}
}
##################################################
#Prepare body in HTML format for Instance
##################################################
if($result1 -ne $null)
{
$Outputreport = "<HTML><TITLE>PMR Website Availability Report</TITLE><BODY background-color:peachpuff><font color =""#99000"" face=""Microsoft Tai le""><H2> PavCap Instance Availability Report </H2></font><Table border=1 cellpadding=0 cellspacing=0><TR bgcolor=gray align=center><TD><B>Instance Name</B></TD><TD><B>InsStatus</B></TD></TR>"
Foreach($Entry1 in $Result1)
{
if($Entry1.InsStatus -eq "Started")
{
$Outputreport += "<TR bgcolor=lightgreen>"
}
else
{
$Outputreport += "<TR bgcolor=red>"
}
$Outputreport += "<TD align=center>$($Entry1.InsName)</TD><TD align=center>$($Entry1.InsStatus)</TD></TR>"
}
$Outputreport += "</Table></BODY></HTML>"
$Outputreport +="<footer><p>This is a system generated email, please do not reply to this email, thank you. For time being, the email addresses are controlling from the script until solution found.</p></footer>"
}
$Outputreport | out-file D:\PS\CheckPavcapWebpage\siteavailabilityrpt.html -Append
$htmlfilename = "D:\PS\CheckPavcapWebpage\siteavailabilityrpt.html"
############################################################################
## Email to users (hardcoding email address on the top of scirpt - declare
###########################################################################
$htmlbodyreport = Get-Content "$htmlfilename" -Raw
Send-MailMessage -to $lrecipients -from $lsender -Subject $lemailsubject -BodyAsHtml -body $htmlbodyreport -SmtpServer "abc.bab.cbb.com"
I got a little powershell problem troubling me for quite a while now.
Im trying to get information from a RSS site. I download the XML and go through it. I just want certain stuff from it. That for I use .document.getElementByID().outerText
The problem is that somehow it pulls the first information correctly but after that everything fails he just picks random text or just keeps the one text from the beginning without refreshing the variable. Also Powershell ISE says "You cannot call a method on a null-valued expression." randomly.
Here is my code:
<#
AUTHOR: KOCH,MICHAEL [GRE-IT]
DESCRIPTION: RSS READER
DATE: 28.06.17
DATE LAST WRITTEN: 19.07.17
LAST CHANGE:
#>
$debug = 1 #DEBUG
$receiver="A#MailAdress.com"
$sender="A#MailAdress.com"
$smtp="A.SMTP.SERVER"
$encoding = [System.Text.Encoding]::UTF8
$path_config = "C:\RSS\Zoll\config.txt"
$output = "C:\RSS\Zoll\meldung.html"
$output_edit_path = "C:\RSS\Zoll\meldung_edit.html"
$nmbr=0
$count=0
Invoke-WebRequest -Uri 'http://www.zoll.de/SiteGlobals/Functions/RSSFeed/DE/RSSNewsfeed/RSSZollImFokus.xml' -OutFile C:\RSS\Zoll\meldungen.xml -ErrorAction Stop
[xml]$content = Get-Content C:\RSS\Zoll\meldungen.xml
$feed = $content.rss.channel
$tag = #()
if($lines=Get-Content $path_config | Measure-Object -Line) #gets the number of lines
{
while($count -ne $lines.Lines)
{
if($entrys=(Get-Content $path_config)[$nmbr]) #gets the entrys from config.txt and goes through line by line
{
$entrys >> $tag[$nmbr]
if ($debug -eq 1)
{
Write-Output "$tag[$nmbr]"
Write-Output "$entrys"
Write-Output "$count"
}
}
$count++
$nmbr++ #jumps into the next line
}
}
$ie = New-Object -ComObject "InternetExplorer.Application"
Foreach($msg in $feed.Item)
{
$link = ($msg.link)
$subject = ($msg.title)
$ie.navigate("$link")
#$return = Invoke-WebRequest -Uri $link -OutFile "C:\RSS\Zoll\link.html"
$return = $ie.document
$innertext = $return.documentElement.document.getElementById("main").outerText
$body = $innertext#.Replace('Ä', 'Ä')
<#
$body = $innertext.Replace('ä', 'ä')
$body = $innertext.Replace('Ö', 'Ö')
$body = $innertext.Replace('ö', 'ö')
$body = $innertext.Replace('Ü', 'Ü')
$body = $innertext.Replace('ü', 'ü')
$body = $innertext.Replace('ß', 'ß')
#>
if ($debug -eq 1)
{
Write-Output "Subject $subject"
Write-Output "Tag $tag"
Write-Output "Link $link"
Write-Output $body
#exit
}
if($link -match "Zigaretten") #searchs in the <link> for the string "Zigaretten"
{
if($subject -match $tag) #searches for the specified tag in config.txt !!! only one argument per line !!!
{
if($mail = Send-MailMessage -From "$sender" -To "$receiver" -Subject "Zoll Meldung: $subject" -Body "$body" -SmtpServer "$smtp" -BodyAsHtml -encoding $encoding)
{
if($debug -eq 1)
{
Write-Output "$tag"
Write-Output "Send. Tag = $tag"
}
Write-Output "Send."
}
}
}
else
{
Write-Host "Empty."
}
}
$ie.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($ie)
Remove-Variable ie
Added a wait if busy loop to make sure IE loads the full html document. Thats the solution of the problem ! :)
<#
AUTHOR: KOCH,MICHAEL [GRE-IT]
DESCRIPTION: RSS READER
DATE: 28.06.17
DATE LAST WRITTEN: 20.07.17
LAST CHANGE: ADDED WAIT IF BUSY !
#>
$debug = 0 #DEBUG
$receiver="A#MailAdress.de"
$sender="A#MailAdress.de"
$smtp="A.SMTP.SERVER"
$encoding = [System.Text.Encoding]::UTF8
$path_config = "C:\RSS\Zoll\config.txt"
$output = "C:\RSS\Zoll\meldung.html"
$output_edit_path = "C:\RSS\Zoll\meldung_edit.html"
$nmbr=0
$count=0
Invoke-WebRequest -Uri 'http://www.zoll.de/SiteGlobals/Functions/RSSFeed/DE/RSSNewsfeed/RSSZollImFokus.xml' -OutFile C:\RSS\Zoll\meldungen.xml -ErrorAction Stop
[xml]$content = Get-Content C:\RSS\Zoll\meldungen.xml
$feed = $content.rss.channel
$tag = #()
if($lines=Get-Content $path_config | Measure-Object -Line) #gets the number of lines
{
while($count -ne $lines.Lines)
{
if($entrys=(Get-Content $path_config)[$nmbr]) #gets the entrys from config.txt and goes through line by line
{
$entrys >> $tag[$nmbr]
if ($debug -eq 1)
{
Write-Output "$tag[$nmbr]"
Write-Output "$entrys"
Write-Output "$count"
}
}
$count++
$nmbr++ #jumps into the next line
}
}
$ie = New-Object -ComObject InternetExplorer.Application #creates new ComObject IE
Foreach($msg in $feed.Item)
{
$link = ($msg.link)
$subject = ($msg.title)
if ($debug -eq 1)
{
$ie.visible = $true
}
$ie.navigate("$link") #navigate with Internetexplorer to the website
while ($ie.busy -and $ie.ReadyState -ne 4){ sleep -Milliseconds 200 } # if getting the website from IE.navigate is still .busy wait 200 milliseconds
$return = $ie.document
$innertext = $return.documentelement.document.IHTMLDocument3_getElementById("main").outerText #gets the outer text from the div with the element ID "main"
while ($innertext.busy -and $innertext.ReadyState -ne 4){ sleep -Milliseconds 200 } # if getting Text is .busy wait 200 milliseconds
$body = $innertext
if ($debug -eq 1)
{
Write-Output "Subject $subject"
Write-Output "Tag $tag"
Write-Output "Link $link"
Write-Output "INNERTEXT $innertext"
Write-Output "BODY $body"
#exit
}
if($link -match "Zigaretten") #searchs in the <link> for the string "Zigaretten"
{
if($subject -match $tag) #searches for the specified tag in config.txt !!! only one argument per line !!!
{
if($mail = Send-MailMessage -From "$sender" -To "$receiver" -Subject "Zoll Meldung: $subject" -Body "$body" -SmtpServer "$smtp" -BodyAsHtml -encoding $encoding)
{
Write-Output "Send."
}
}
}
else
{
Write-Host "Empty."
}
}
$ie.Quit() #----|
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($ie) # ---> Quits the Internet Explorer Session otherwise there are to many IE.exe open and no more ID's left
Remove-Variable ie
I have a script on powershell that when it runs it send an email out with server status details and also prints the information on screen
I am looking now to add to the script that aswell as sending the email and prints the information on screen it also saves the results on notepad and saves it in a folder on the shared drive
I am new to powershell so not sure how i go about doing that. I can add my code if needed
thanks
os
the code is
$DirectoryPath = Split-Path $MyInvocation.MyCommand.Path
$ConfigurationPath = $DirectoryPath + '\Config file.xml'
Function FormatCell
{
param($cellValue)
$cell = "<td>" + $cellValue + "</td>"
return $cell
}
Function Getservicechecker
{
[xml]$ConfigFile = Get-Content $ConfigurationPath
$Servers = $ConfigFile.SelectNodes('/Configs/Servers/Server')
$ServString = "<tr><th>Server</th><th>IP Address</th><th>Process</th> <th>Status</th></tr>"
foreach($Server in $Servers)
{
[string]$serverName = $Server.ServerName
$OutputText += "Server: " + $serverName + $NL
$Process = $Server.ProcessesToMonitor
foreach($Processtomonitor in $Process.ChildNodes)
{
$ServString += "<tr>"
$ServString += FormatCell -cellValue $serverName
$ipaddress = Test-Connection $serverName -count 1 | select Ipv4Address
$ipAddressValue = $ipaddress.IPV4Address.IPAddressToString
$servString += FormatCell -cellValue $ipAddressValue
[string]$processName = $Processtomonitor.InnerText
$servicestatus = Get-service -ComputerName $serverName -Name $processName | select status
$ServString += FormatCell -cellValue $processName
$FormatedStatus = 'status'
[string]$statusString = -join $servicestatus
$statusString = $statusString.Remove(0,"#{Status=".Length)
$statusString = $statusString.Remove($statusString.IndexOf("}"))
$FormatedServiceStatus = FormatCell -cellValue $servicestatus
If ($FormatedServiceStatus –eq “<td>#{Status=Running}</td>”)
{
$Formatedstatus = 'Running'
}
elseif ($FormatedServiceStatus –eq “<td>#{Status=Stopped}</td>”)
{
$Formatedstatus = "<p style='color:red'>Service stopped investigation required</p>"
}
else
{
$FormatedStatus = "$servicestatus potential investigation"
}
Write-host "server: $serverName `t ipaddress: $ipAddressValue `t process: $processName `t status: $statusString"
$ServString += FormatCell -cellValue $Formatedstatus
$ServString += "</tr>"
}
}
return "<table class=""gridtable"">" + $ServString + "</table>"
}
function SendMail
{
param($bodyText, $subject )
$SmtpServer = "164.134.84.81"
$emailMessage = New-Object System.Net.Mail.MailMessage
$fromaddress = "osman.test.farooq#gmail.com"
$recipients = ("osman.farooq#atos.net")
$Subject = "BOXI Servers Report for " +$dateTimeOfServiceCheck
$body = "<HTML><HEAD><META http-equiv=""Content-Type"" content=""text/html; charset=iso-8859-1"" /><TITLE></TITLE>"
$body += "<style type=""text/css"">table.gridtable {font-family: verdana,arial,sans-serif;font-size:11px;color:#333333;border-width: 1px;border-color: #666666;border-collapse: collapse;}"
$body += "table.gridtable th {border-width: 1px;padding: 8px;border-style: solid;border-color: #666666; background-color: #dedede;}"
$body += "table.gridtable td {border-width: 1px;padding: 8px;border-style: solid;border-color: #666666; background-color: #ffffff;}</style></HEAD>"
$body += "<BODY bgcolor=""#FFFFFF"" style=""font-size: Small; font-family: TAHOMA; color: #000000"">"
$body += $bodyText
Send-MailMessage -to $recipients -subject $subject -bodyashtml -body $body - from $fromAddress -SmtpServer $smtpServer -Port 25
}
function main
{
$dateTimeOfServiceCheck = Get-Date -Format F
$outputText = "Service Checker :" + $dateTimeOfServiceCheck
$emailBody = "<h3>"+$outputText +"</h3>" #take out if dont want datetime above table
$emailBody += Getservicechecker
SendMail $emailBody "BOXI Servers Report for" +$dateTimeOfServiceCheck
}
main
Trevor's answer covers writing the file pretty well. Once the file is written, you could open it in the default application using Invoke-Item:
$myPath = 'C:\my\file.txt'
$information | Set-Content -Path $myPath
$mypath | Invoke-Item
There are many approaches to writing files in PowerShell. Which one you use is entirely up to you!
Use the Set-Content command
Use the Out-File command
Use the [System.IO.File]::WriteAllText() method
As Mathias mentions in the comments, the Tee-Object command can be used to write to a file and simultaneously send it down the pipeline, or write the contents to a variable. There are probably even more approaches as well.
I have a script which reads a file of URL's and then performs a webrequest to check the status and latency of a list of site portals. We present this in a html table on an internal webserver. Our urls are not very meaningful to our business users I would like to create a new column in the table which shows the name of the site (http://10.x.x.x:8080/portal would be named 'Manchester')
Preferably reading in another file of names as each line of both files will match up
I have been doing this as a vanity project when I have a bit of free time in work but have limited knowledge.
'## The URI list to test
$URLListFile = "H:\Scripts\web.txt"
$URLList = Get-Content $URLListFile -ErrorAction SilentlyContinue
$Result = #()
$a = Get-date
Foreach($Uri in $URLList) {
$time = try
{
$request = $null
## Request the URI, and measure how long the response took.
$result1 = Measure-Command { $request = Invoke-WebRequest -Uri $uri }
$result1.TotalMilliseconds
}
catch
{
<# If the request generated an exception (i.e.: 500 server
error or 404 not found), we can pull the status code from the
Exception.Response property #>
$request = $_.Exception.Response
$time = -1
}
$result += [PSCustomObject] #{
Time = Get-Date;
Uri = $uri;
StatusCode = [int] $request.StatusCode;
StatusDescription = $request.StatusDescription;
ResponseLength = $request.RawContentLength;
TimeTaken = $time;
}
$SResult += [PSCustomObject] #{
Store = $Store;
}
}
#Prepare email body in HTML format
if($result -ne $null)
{
$Outputreport = "<HTML><TITLE>Stores Web Portal Status</TITLE><BODY background-color:peachpuff><font color =""#99000"" face=""Microsoft Tai le""><H2> Stores Web Portal Status $($a)</H2></font><Table border=1 cellpadding=0 cellspacing=0><TR bgcolor=gray align=center><TD><B>URL</B></TD><TD><B>StatusCode</B></TD><TD><B>StatusDescription</B></TD><TD><B>ResponseLength</B></TD><TD><B>TimeTaken</B></TD</TR>"
Foreach($Entry in $Result)
{
if($Entry.StatusCode -ne "200")
{
$Outputreport += "<TR bgcolor=red>"
}
else
{
$Outputreport += "<TR bgcolor=green>"
}
if($Entry.timetaken -ge "2600.000")
{
$Outputreport += "<TR bgcolor=yellow>"
}
$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 H:\Scripts\Test.htm'
I recommend changing the source file to a CSV format that stores both the URI and the Name side-by-side. In concept, it would look something like this:
$csvText = #"
Uri,SiteName
http://10.0.0.1/foo,Foo
http://10.0.0.2/bar,Bar
"#
$siteRecords = ConvertFrom-Csv $csvText
$siteRecords
In practice, you would use Import-Csv to get the data from your file, and then you would have access to both properties when iterating.
$siteRecords = Import-Csv -Path $pathToYourCsvFile
foreach ($record in $siteRecords)
{
$record.Uri
$record.SiteName
}