I have written a validation script with few tests and the script run locally on each machine with help of a tool. But for running only below script part successfully the domain username and password to be invoked.
Can anyone help me adding username and password to invoke below script ( eg: username : oim\test , password : test#123 )
if (($ImageName -like "*devel*") -or ($ImageName -like "*hosted*"))
{
#$ADE1 = Invoke-Expression ('C:\ade\bin\ade.exe | select-string -pattern "begintrans"') | out-string ; $ADE = $ADE1.trim().split("")[1]
Invoke-Expression ('C:\ade\bin\ade.exe | select-string -pattern "begintrans"') > C:\Temp\ade_check.txt
$ADE1 = Get-Content C:\Temp\ade_check.txt | Select-String "begintrans" | out-string ; $ADE = $ADE1.trim().split(" ")[1]
if ($ADE -eq "begintrans")
{
$ADE = "ADE Installation Success"
Add-Content $report "<tr>"
Add-Content $report "<td bgcolor= 'White' height='30' align=center><B>17</B></td>"
Add-Content $report "<td bgcolor= 'White' height='30' align=left><B>ADE</B></td>"
Add-Content $report "<td bgcolor= 'Aquamarine' height='30' align=left><B>$ADE</B></td>"
Add-Content $report "</tr>"
echo "ADE = ADE Installation Success"
}
if ($ADE -eq $null){
$ADE = "ADE Installation Failed"
Add-Content $report "<tr>"
Add-Content $report "<td bgcolor= 'White' height='30' align=center><B>17</B></td>"
Add-Content $report "<td bgcolor= 'White' height='30' align=left><B>ADE</B></td>"
Add-Content $report "<td bgcolor= 'red' height='30' align=left><B>$ADE</B></td>"
Add-Content $report "</tr>"
echo "ADE = ADE Installation Failed"
}
}
else
{
if (($ImageName -like "*simple*") -or ($ImageName -like "*BareOS*")){
$ADE = "BareOS, ADE Not Installed"
Add-Content $report "<tr>"
Add-Content $report "<td bgcolor= 'White' height='30' align=center><B>17</B></td>"
Add-Content $report "<td bgcolor= 'White' height='30' align=left><B>ADE</B></td>"
Add-Content $report "<td bgcolor= 'Yellow' height='30' align=left><B>$ADE</B></td>"
Add-Content $report "</tr>"
echo "ADE = BareOS, ADE Not Installed"
}
}
You want to use Invoke-Command cmdlet instead. It has -Credentials parameter that you want. Like this:
$UserName='oim\test'
$UserPassword='test#123'
$Password = (ConvertTo-SecureString -String $UserPassword -AsPlainText -Force)
$Credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList #($UserName, $Password)
Invoke-Command -ScriptBlock { & 'C:\ade\bin\ade.exe' | Select-String -Pattern 'begintrans' > C:\Temp\ade_check.txt } -Credential $Credentials -ComputerName $env:COMPUTERNAME
Related
But when I am testing this locally its working fine when I tried to test in AD server script going for loop and sending email and trying to start service even service is up and running.
Function email {$EmailTo = "xxxxxx"$EmailFrom = "xcxcxcx"$date = ( get-date ).To String('MM/dd/yyyy')$EmailSubject = "servername - Services " + $date$SMTPServer = "sfgte.fthdd.net"$Username ="xxxxxkey"$Password = ConvertTo-SecureString "xcvcbfrd" -As Plaintext -Force$credential = New-Object System.Management.Automation.PSCredential $Username, $Password
$BodyReport = Get-Content ".\ServiceFileNam.htm" -Raw
Send-MailMessage -smtpServer $SmtpServer -Credential $credential -Usessl -Port 587 -from $EmailFrom -to $EmailTo -subject $EmailSubject -BodyAsHtml -Body $BodyReport}
Function Get-ServiceStatusReport{param([String[]]$includeService,[String]$To,[String]$From,[string]$SMTPMail)
$ServerName = 'servername'$ServiceFileName= "ServiceFileNam.htm"
$message = 'test'
$restartsuccessmessage = ' Services Successfully Restarted by Script'$restartedfailuremessage = 'Script not able to start the Services'$failuremessage = ' Services on servernamefound stopped.'New-Item -ItemType file $ServiceFilename -Force
Function to write the HTML Header to the file
Function writeHtmlHeader{param($fileName)$date = ( get-date ).To String('yyyy/MM/dd')Add-Content $fileName "<html>"Add-Content $fileName "<head>"Add-Content $fileName "<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>"Add-Content $fileName '<title>Service Status Report </title>'add-content $fileName '<STYLE TYPE="text/css">'add-content $fileName "<!--"add-content $fileName "td {"add-content $fileName "font-family: Tahoma;"add-content $fileName "font-size: 11px;"add-content $fileName "border-top: 1px solid #999999;"add-content $fileName "border-right: 1px solid #999999;"add-content $fileName "border-bottom: 1px solid #999999;"add-content $fileName "border-left: 1px solid #999999;"add-content $fileName "padding-top: 0px;"add-content $fileName "padding-right: 0px;"add-content $fileName "padding-bottom: 0px;"add-content $fileName "padding-left: 0px;"add-content $fileName "}"add-content $fileName "body {"add-content $fileName "margin-left: 5px;"add-content $fileName "margin-top: 5px;"add-content $fileName "margin-right: 0px;"add-content $fileName "margin-bottom: 10px;"add-content $fileName ""add-content $fileName "table {"add-content $fileName "border: thin solid #000000;"add-content $fileName "}"add-content $fileName "-->"add-content $fileName "</style>"Add-Content $fileName "</head>"Add-Content $fileName "<body>"
add-content $fileName "<table width='100%'>"
add-content $fileName "<tr bgcolor='#CCCCCC'>"
add-content $fileName "<td colspan='4' height='25' align='center'>"
add-content $fileName "<font face='tahoma' color='#003399' size='4'><strong>servername - Services Status - $date</strong></font>"
add-content $fileName "</td>"
add-content $fileName "</tr>"
add-content $fileName "</table>"
}Function writeHtmlbody{param($ServiceFileName,$message)
Add-Content $ServiceFileName "<table width='100%'><tbody>"
Add-Content $ServiceFileName "<tr bgcolor='#CCCCCC'>"
Add-Content $ServiceFileName "<td width='100%' align='left' colSpan=3><font face='tahoma' color='#003399' size='2'><strong>Hi Team</strong> </br></br>
$message</font></td>"
Add-Content $ServiceFileName "</tr>"
Function to write the HTML Header to the file
Function writeTableHeader{param($fileName)
Add-Content $fileName "<tr bgcolor=#CCCCCC>"
Add-Content $fileName "<b><td width='35%' align='center'><b>ServerName</b></td></b>"
Add-Content $fileName "<b><td width='35%' align='center'><b>Service Name</b></td></b>"
Add-Content $fileName "<b><td width='35%' align='center'><b>Status</b></td></b>"
Add-Content $fileName "</tr>"
}
Function writeHtmlFooter{param($fileName)
Add-Content $fileName "</body>"
Add-Content $fileName "</html>"
}
Function writeDiskInfo{param($filename,$Servername,$name,$Status)if( $status -eq "Stopped"){Add-Content $fileName "<tr>"Add-Content $fileName "<td bgcolor='#FF0000' align=center >$servername</td>"Add-Content $fileName "<td bgcolor='#FF0000' align=center >$name</td>"Add-Content $fileName "<td bgcolor='#FF0000' align=center >$Status</td>"Add-Content $fileName "</tr>"}else{Add-Content $fileName "<tr>"Add-Content $fileName "<td >$servername</td>"Add-Content $fileName "<td >$name</td>"Add-Content $fileName "<td bgcolor='#6EEE6E' align=left >$Status</td>"#Add-Content $fileName "<td >$Status</td>"Add-Content $fileName "</tr>"}}
writeHtmlHeader $ServiceFileName
Add-Content $ServiceFileName "<table width='100%'><tbody>"
Add-Content $ServiceFileName "<tr bgcolor='#CCCCCC'>"
Add-Content $ServiceFileName "<td width='100%' align='left' colSpan=3><font face='tahoma' color='#003399' size='2'>Hi Team <br<br
Below Service has been stopped in the server.Kindly create ticket and assgine to Team<br<br
Thankyou</font></td>"
Add-Content $ServiceFileName "</tr>"
writeTableHeader $ServiceFileName
#Change value of the following parameter as needed
$InlcudeArray=#()
#List of programs to exclude#$InlcudeArray = $inlcudeService
if(Test-Connection -ComputerName $ServerName -Count 1 -ea 0){$service = Get-Service -ComputerName $ServerNameif ($service -ne $NULL){foreach ($item in $service){#$item.DisplayNameForeach($include in $includeService){write-host $inlcudeif(($item.serviceName).Contains($include) -eq $TRUE){#Write-Host $item.MachineName $item.name $item.Status$status = $item.Status# writeDiskInfo $ServiceFileName $item.MachineName $item.name $item.Statusif($status -eq 'Running'){#Write-Host 'running'Break}elseif($status -eq 'Stopped'){#Write-Host 'Stopped'
$emessage = '</br> This is an automated message to confirm that the Services on Servername
found stopped. Automation script is restarting the service.Please wait 5 mins for the next email with service status update.<br
```
<brThank You,<brTools and Automation Team'writeHtmlHeader $ServiceFileNamewriteHtmlbody $ServiceFileName $emessagewriteTableHeader $ServiceFileNamewriteDiskInfo $ServiceFileName $item.MachineName $item.name $item.Statusemail# Start serviceGet-Service -ComputerName 'servername' -Name 'service name' | Start-Service -Verbose
Sleep -Seconds 20
$service = Get-Service -ComputerName $ServerName
if ($service -ne $NULL)
{
foreach ($item in $service)
{
#$item.DisplayName
Foreach($include in $includeService)
{
write-host $inlcude
if(($item.serviceName).Contains($include) -eq $TRUE)
{
#Write-Host $item.MachineName $item.name $item.Status
$status = $item.Status
if ($status -eq 'Running')
{
#Write-Host 'Started'
$message = '</br>This mail confirms that the Services on servername has been started by automation script is up and running now and no further action required.</br>
</br>Thank You,</br>
Tools and Automation Team'
Clear-Content ".\ServiceFileNam.htm"
writeHtmlHeader $ServiceFileName
writeHtmlbody $ServiceFileName $message
writeTableHeader $ServiceFileName
writeDiskInfo $ServiceFileName $item.MachineName $item.name $item.Status
email
}
elseif($status -ne 'Running')
{
#Write-Host 'Stopped'
Clear-Content ".\ServiceFileNam.htm"
$message = '</br> Services on servername is not up after script execution.Kindly create ticket and assgine to Team for validation.</br>
</br>Thank You,</br>
Tools and Automation Team'
writeHtmlHeader $ServiceFileName
writeHtmlbody $ServiceFileName $message
writeTableHeader $ServiceFileName
writeDiskInfo $ServiceFileName $item.MachineName $item.name $item.Status
email
}
}
}
}
}
}
}
}
}
}
}}
#Add-Content $ServiceFileName "</table>"#writeHtmlFooter $ServiceFileName
Get-ServiceStatusReport -ComputerList "servername" -includeService "serviceName"
I have prepared server health report via PowerShell. My script is working fine but I am getting some random value in the bottom when I receive email via script, also I am not able to add body in my send-mailmessage command. When I do so script generates exception.
Here is my PS code:
<#
.SYNOPSIS
Script for the detailed server health report
.DESCRIPTION
The script accepts parameter from CSV file by which we can get details and
all information related to health status of the server.The script generates all the
information in a CSv file.
#>
[CmdletBinding(SupportsShouldProcess=$True)]
param(
[Parameter(Position=0,mandatory=$true)]
[string]$Servercsv
)
begin{
Write-Host "Running"
}
process{
# Path for the CSV file that contains all the Print Server information.
$ServerDetails=import-csv $Servercsv
$result=#()
$Outputreport = $null
foreach($server in $ServerDetails){
try{
#sysinfo variable contains complete systeminfo like manufacturer name, physical memory,servername
$cpu=Get-WMIObject -ComputerName $server.servers win32_processor| select __Server, #{name="CPUUtilization" ;expression ={“{0:N2}” -f (get-counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 1 -MaxSamples 5 |
select -ExpandProperty countersamples | select -ExpandProperty cookedvalue | Measure-Object -Average).average}}
$disks =Get-WmiObject -Class win32_Volume -ComputerName $server.servers -Filter "DriveLetter = 'C:'" |
Select-object #{Name = "PercentFree"; Expression = {“{0:N2}” -f (($_.FreeSpace / $_.Capacity)*100) } }
$os=gwmi -Class win32_operatingsystem -computername $server.servers |
Select-Object #{Name = "MemoryUsage"; Expression = {“{0:N2}” -f ((($_.TotalVisibleMemorySize - $_.FreePhysicalMemory)*100)/ $_.TotalVisibleMemorySize) }}
$result += [PSCustomObject] #{
ServerName ="$($server.servers)"
CPUUtilization = $cpu.CPUUtilization.ToString()
CDrive = $disks.PercentFree
MemLoad = $OS.MemoryUsage
}
}
catch{
"error communicating with $($server.servers), skipping to next"
}
}
$Outputreport = "<HTML><TITLE> Utilization of Server Resources</TITLE>
<BODY background-color:peachpuff>
<font color =""#99000"" face=""arial"">
<H3> Utilization of Server Resources</H3></font>
<Table border=2 cellpadding=1 cellspacing=5>
<TR bgcolor=gray align=center>
<TD><B>Server Name</B></TD>
<TD><B>CPUUtilization</B></TD>
<TD><B>Memory Utilization</B></TD>
<TD><B>CDrive</B></TD></TR>"
Foreach($Entry in $Result){
if(([decimal]$Entry.CPUUtilization -ge 15) -or ([decimal]$Entry.MemLoad -ge 50) -or (([decimal]$Entry.CDrive) -le 60) )
{
$Outputreport += "<TR>"
$Outputreport += "<TD><B>$($Entry.Servername)</B></TD>"
if([decimal]$Entry.CPUUtilization -ge 15)
{
$Outputreport += "<TD align=center style=color:red;>$($Entry.CPUUtilization+'%')</TD>"
}
else {
$Outputreport += "<TD align=center style=color:White;>$($Entry.CPUUtilization+'%')</TD>"
}
if([decimal]$Entry.MemLoad -ge 50)
{
$Outputreport += "<TD align=center style=color:red;>$($Entry.MemLoad+'%')</TD>"
}
else{
$Outputreport += "<TD align=center style=color:White;>$($Entry.MemLoad+'%')</TD>"
}
if(([decimal]$Entry.CDrive) -le 60)
{
$Outputreport += "<TD align=center style=color:red;>$($Entry.Cdrive+'%')</TD>"
}
else{ $Outputreport += "<TD align=center style=color:White;>$($Entry.Cdrive+'%')</TD>"}
#$Outputreport += "<TD>$($Entry.Servername)</TD>"
#$Outputreport += "<TD>$($Entry.Servername)</TD>"
$Outputreport+="</TR>"
}
}
$Outputreport += "</Table><p>Hello</p></BODY></HTML>"
$out=$Outputreport | ConvertTo-Html -Head $Outputreport
#Send an email about the Load
# $smtp is the outgoing mail server
$smtp= "smtphost.redmond.corp.microsoft.com"
try{
send-mailmessage -SmtpServer $smtp -from v-rubhat#microsoft.com -to v-rubhat#microsoft.com -subject "Server Health Report" -BodyAsHtml "$out"
}
catch [exception]
{
write-host ("Cannot send mail, since argument is null or empty")
}
}
Below is my attached output and that * and 1121 is that random number:
Utilization of Server Resources
Server Name CPUUtilization Memory Utilization CDrive
xxxxxxxx 3.25% 29.26% 22.11%
xxxxxxxx 18.80% 52.15% 57.49%
xxxxxxxx 27.76% 27.51% 71.91%
*
1121
I have changed the $out variable and added property attribute in it and that worked. Here's my edited $out command
$out=$Outputreport | ConvertTo-Html -Property Servername,CPUUtilization,MemLoad,CDrive -Head $Outputreport
I have written a powershell script to query NIC binding order and the script will look NIC binding order in the format Vethernet,storage if this order is correct then it will print output in green color else it will print in yellow color.
Also I have added one more condition here, i.e if there is no storage NIC found in the binding order it should see Vethernet is the first in order and if the order correct,it should print as green or else it should be yellow.But there seems to be some problem with my script.
The first if condition line work perfect, but the second else if condition doesn't work well. I have tried changing the order , even after changing order it print the color as green.
Can anyone help me correcting this script ?
$results = Invoke-Command -ComputerName $ComputerName {(Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Linkage").Bind | ForEach-Object {
$guid = ($_ -split '\\')[2]
Get-WmiObject -Query "SELECT * FROM Win32_NetworkAdapter WHERE GUID='$guid'" |
Select-Object -ExpandProperty NetConnectionID
}}
$adapteresult = $results -join","
if (($adapteresult.Contains('Storage') -and ($adapteresult -match 'vEthernet\s+\([^)]+\),storage')))
{
Add-Content $report "<td bgcolor= 'Aquamarine' height='25' align=center><B>$adapteresult</B></td>"
}
elseif ($adapteresult -NotContains "Storage" -and ($adapteresult -match 'vEthernet\s+\([^)]+\),'))
{
Add-Content $report "<td bgcolor= 'Aquamarine' height='25' align=center><B>$adapteresult</B></td>"
}
else
{
Add-Content $report "<td bgcolor= 'Yellow' height='25' align=center><B>$adapteresult</B></td>"
}
To be more precise, you can check the with $Null
Just add the Condition with OR like :
if (($adapteresult -match 'vEthernet\s+\([^)]+\),storage') -or ($adapteresult -eq $null))
As per the update, Why to use multiple if else:
if( ($adapteresult -match 'vEthernet\s+\([^)]+\),storage') -or ($adapteresult -match 'vEthernet*\s+\([^)]+\),') )
{
Add-Content $report "<td bgcolor= 'Aquamarine' height='25' align=center><B>$adapteresult</B></td>"
}
else
{
Add-Content $report "<td bgcolor= 'Yellow' height='25' align=center><B>$adapteresult</B></td>"
}
I have a big script where I need to add a condition that when ever below ADE checks failed (i.e ADE Installation Failed), the entire script status should change to Failed. Can anyone please help me here to add a condition?
if (($ImageName -like "*devel*") -or ($ImageName -like "*hosted*"))
{
#$ADE1 = Invoke-Expression ('C:\ade\bin\ade.exe | select-string -pattern "begintrans"') | out-string ; $ADE = $ADE1.trim().split("")[1]
Invoke-Expression ('C:\ade\bin\ade.exe | select-string -pattern "begintrans"') > C:\Temp\ade_check.txt
#Invoke-Command -ScriptBlock { & 'C:\ade\bin\ade.exe' | Select-String -Pattern 'begintrans' > C:\Temp\ade_check.txt } -Credential $Credentials -ComputerName $env:COMPUTERNAME
$ADE1 = Get-Content C:\Temp\ade_check.txt | Select-String "begintrans" | out-string ; $ADE = $ADE1.trim().split(" ")[1]
if ($ADE -eq "begintrans")
{
$ADE = "ADE Installation Success"
Add-Content $report "<tr>"
Add-Content $report "<td bgcolor= 'White' height='30' align=center><B>17</B></td>"
Add-Content $report "<td bgcolor= 'White' height='30' align=left><B>ADE</B></td>"
Add-Content $report "<td bgcolor= 'Aquamarine' height='30' align=left><B>$ADE</B></td>"
Add-Content $report "</tr>"
echo "ADE = ADE Installation Success"
}
if ($ADE -eq $null){
$ADE = "ADE Installation Failed"
Add-Content $report "<tr>"
Add-Content $report "<td bgcolor= 'White' height='30' align=center><B>17</B></td>"
Add-Content $report "<td bgcolor= 'White' height='30' align=left><B>ADE</B></td>"
Add-Content $report "<td bgcolor= 'red' height='30' align=left><B>$ADE</B></td>"
Add-Content $report "</tr>"
echo "ADE = ADE Installation Failed"
}
}
else
{
if (($ImageName -like "*simple*") -or ($ImageName -like "*BareOS*")){
$ADE = "BareOS, ADE Not Installed"
Add-Content $report "<tr>"
Add-Content $report "<td bgcolor= 'White' height='30' align=center><B>17</B></td>"
Add-Content $report "<td bgcolor= 'White' height='30' align=left><B>ADE</B></td>"
Add-Content $report "<td bgcolor= 'Yellow' height='30' align=left><B>$ADE</B></td>"
Add-Content $report "</tr>"
echo "ADE = BareOS, ADE Not Installed"
}
}
You should never fail a script in that way, rather you should use try/catch block in order to catch that. But if you still wish to fail the script the moment "ADE Installation failed", then you can use the forcefully exit command to fail the script.
Instead of this:
if ($ADE -eq $null){
$ADE = "ADE Installation Failed"
Add-Content $report "<tr>"
Do this:
if ($ADE -eq $null){
$ADE = "ADE Installation Failed"
exit 1
Add-Content $report "<tr>"
Im stuck in a Filtering / Formating issue.
Goal:
Provide a customer readable output exported to HTML for easy viewing.
Required:
Filtering multiple services along with their data to be displayed in the report.
Issue:
Gathering/Parsing the data in its needed form using win32_service to query specific services.
#CODE
# First lets create a text file, where we will later save the Service Health info
$ServiceHealthFileName = "ServiceHealth.htm"
$serverlist = "mylistofservers.txt"
$warning = "Stopped"
New-Item -ItemType file $ServiceHealthFileName -Force
# Function to write the HTML Header to the file
Function writeHtmlHeader
{
param($fileName)
$date = ( get-date ).ToString('yyyy/MM/dd')
Add-Content $fileName "<html>"
Add-Content $fileName "<head>"
Add-Content $fileName "<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>"
Add-Content $fileName '<title> Server Health</title>'
add-content $fileName '<STYLE TYPE="text/css">'
add-content $fileName "<!--"
add-content $fileName "td {"
add-content $fileName "font-family: Tahoma;"
add-content $fileName "font-size: 11px;"
add-content $fileName "border-top: 1px solid #999999;"
add-content $fileName "border-right: 1px solid #999999;"
add-content $fileName "border-bottom: 1px solid #999999;"
add-content $fileName "border-left: 1px solid #999999;"
add-content $fileName "padding-top: 0px;"
add-content $fileName "padding-right: 0px;"
add-content $fileName "padding-bottom: 0px;"
add-content $fileName "padding-left: 0px;"
add-content $fileName "}"
add-content $fileName "body {"
add-content $fileName "margin-left: 5px;"
add-content $fileName "margin-top: 5px;"
add-content $fileName "margin-right: 0px;"
add-content $fileName "margin-bottom: 10px;"
add-content $fileName ""
add-content $fileName "table {"
add-content $fileName "border: thin solid #000000;"
add-content $fileName "}"
add-content $fileName "-->"
add-content $fileName "</style>"
Add-Content $fileName "</head>"
Add-Content $fileName "<body>"
add-content $fileName "<table width='100%'>"
add-content $fileName "<tr bgcolor='#CCCCCC'>"
add-content $fileName "<td colspan='7' height='25' align='center'>"
add-content $fileName "<font face='tahoma' color='#003399' size='4'><strong> Server Health - $date</strong></font>"
add-content $fileName "</td>"
add-content $fileName "</tr>"
add-content $fileName "</table>"
}
# Function to write the HTML Header to the file
Function writeTableHeader
{
param($fileName)
Add-Content $fileName "<tr bgcolor=#CCCCCC>"
Add-Content $fileName "<td width='10%' align='center'>Name</td>"
Add-Content $fileName "<td width='50%' align='center'>ProcessId</td>"
Add-Content $fileName "<td width='10%' align='center'>State</td>"
Add-Content $fileName "<td width='10%' align='center'>StartMode</td>"
Add-Content $fileName "<td width='10%' align='center'>ExitCode</td>"
Add-Content $fileName "<td width='10%' align='center'>Status</td>"
Add-Content $fileName "</tr>"
}
Function writeHtmlFooter
{
param($fileName)
Add-Content $fileName "</body>"
Add-Content $fileName "</html>"
}
Function writeServiceInfo
{
param($fileName,$SvcName,$SvcPID,$SvcSM,$SvcExCd,$ServiceState,$SvcStatus)
$SvcName= $Item.Name
$SvcPID= $Item.ProcessId
$SvcSM= $Item.StartMode
$SvcExCd= $Item.ExitCode
$ServiceState= $Item.State
$SvcStatus= $Item.Status
if ($ServiceState -eq $warning)
{
Add-Content $fileName "<tr>"
Add-Content $fileName "<td>$SvcName</td>"
Add-Content $fileName "<td>$SvcPID</td>"
Add-Content $fileName "<td bgcolor='#FBB917' align=center>$ServiceState</td>"
# #FBB917
Add-Content $fileName "<td>$SvcSM</td>"
Add-Content $fileName "<td>$SvcExCd</td>"
Add-Content $fileName "<td>$SvcStatus</td>"
Add-Content $fileName "</tr>"
}
else
{
Add-Content $fileName "<tr>"
Add-Content $fileName "<td>$SvcName</td>"
Add-Content $fileName "<td>$SvcPID</td>"
Add-Content $fileName "<td>$ServiceState</td>"
Add-Content $fileName "<td>$SvcSM</td>"
Add-Content $fileName "<td>$SvcExCd</td>"
Add-Content $fileName "<td>$SvcStatus</td>"
Add-Content $fileName "</tr>"
}
}
#Function sendEmail
#{ param($from,$to,$subject,$smtphost,$htmlFileName)
#$body = Get-Content $htmlFileName
#$smtp= New-Object System.Net.Mail.SmtpClient $smtphost
#$msg = New-Object System.Net.Mail.MailMessage $from, $to, $subject, $body
#$msg.isBodyhtml = $true
#$smtp.send($msg)
writeHtmlHeader $ServiceHealthFileName
foreach ($server in Get-Content $serverlist)
{
Add-Content $ServiceHealthFileName "<table width='100%'><tbody>"
Add-Content $ServiceHealthFileName "<tr bgcolor='#CCCCCC'>"
Add-Content $ServiceHealthFileName "<td width='100%' align='center' colSpan=6><font face='tahoma' color='#003399' size='2'><strong> $server </strong></font></td>"
Add-Content $ServiceHealthFileName "</tr>"
writeTableHeader $ServiceHealthFileName
$store = Get-WmiObject -Class Win32_Service -ComputerName $name -Filter "Name LIKE 'ss0'" ;Get-WmiObject -Class Win32_Service -ComputerName $name -Filter "Name LIKE 'ss1'";Get-WmiObject -Class Win32_Service -ComputerName $name -Filter "Name LIKE 'ss2'";Get-WmiObject -Class Win32_Service -ComputerName $name -Filter "Name LIKE 'ss3'";Get-WmiObject -Class Win32_Service -ComputerName $name -Filter "Name LIKE 'ss4'";Get-WmiObject -Class Win32_Service -ComputerName $name -Filter "Name LIKE 'ss5'";Get-WmiObject -Class Win32_Service -ComputerName $name -Filter "Name LIKE 'ss6'";Get-WmiObject -Class Win32_Service -ComputerName $name -Filter "Name LIKE 'ss7'"
#The below would not let me create objects in the store it had an error.
#store = Get-WmiObject -Class Win32_Service -ComputerName $name -Filter "Name LIKE 'ss0'"
#$store = $store + Get-WmiObject -Class Win32_Service -ComputerName $name -Filter "Name LIKE 'ss1'"
#$store = $store + Get-WmiObject -Class Win32_Service -ComputerName $name -Filter "Name LIKE 'ss2'"
#$store = $store + Get-WmiObject -Class Win32_Service -ComputerName $name -Filter "Name LIKE 'ss3'"
#$store = $store + Get-WmiObject -Class Win32_Service -ComputerName $name -Filter "Name LIKE 'ss4'"
#$store = $store + Get-WmiObject -Class Win32_Service -ComputerName $name -Filter "Name LIKE 'ss5'"
#$store = $store + Get-WmiObject -Class Win32_Service -ComputerName $name -Filter "Name LIKE 'ss6'"
#$store = $store + Get-WmiObject -Class Win32_Service -ComputerName $name -Filter "Name LIKE 'ss7'"
foreach ($item in $store)
{
Write-Host $item.Name $item.Name $item.FreeSpace $item.Size
writeServiceInfo $ServiceHealthFileName $item.Name $item.ProcessId $item.State $item.StartMode $Item.ExitCode $Item.Status
}
}
writeHtmlFooter $ServiceHealthFileName
$date = ( get-date ).ToString('yyyy/MM/dd')
My output file is populating correctly but only for the first service.
I get the server name and all the statuses exactly how I want them.
Im not sure what I am missing.
Out of respect this is a chopped version of a diskspace script that I got as an example from a coworker. Kudos to the original writer of whom I do not know.
Your only storing one of your service objects into the $store variable, the rest are just being emitted to the pipeline. make $store an array and then add elements to it.
$store = #()
$store += Get-WmiObject -Class Win32_Service -ComputerName $name -Filter "Name LIKE 'ss0'"
$store += Get-WmiObject -Class Win32_Service -ComputerName $name -Filter "Name LIKE 'ss1'"
Also please don't string together multiple lines into one using ; unless you have a really good reason for doing so(which is virtually never in PowerShell), it just makes your code really unclear and doesn't do anything a carriage return doesn't.
The finished code. I added an uptime to the report. Thanks to everyone for the help #MikeGaruccio . Since this was modified from another authors DiskSpace script, Thank you if you see this. In the spirit of the community here is the code for a nice Report of services with a little logic for stopped services.
# First lets create a text file, where we will later save the Service Health info
$ServiceHealthFileName = "ServiceHealth.htm"
$serverlist = "yourserverlist.txt"
$warning = "Stopped"
New-Item -ItemType file $ServiceHealthFileName -Force
# Function to write the HTML Header to the file
Function writeHtmlHeader
{
param($fileName)
$date = ( get-date ).ToString('yyyy/MM/dd')
Add-Content $fileName "<html>"
Add-Content $fileName "<head>"
Add-Content $fileName "<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>"
Add-Content $fileName '<title> Server Health</title>'
add-content $fileName '<STYLE TYPE="text/css">'
add-content $fileName "<!--"
add-content $fileName "td {"
add-content $fileName "font-family: Tahoma;"
add-content $fileName "font-size: 11px;"
add-content $fileName "border-top: 1px solid #999999;"
add-content $fileName "border-right: 1px solid #999999;"
add-content $fileName "border-bottom: 1px solid #999999;"
add-content $fileName "border-left: 1px solid #999999;"
add-content $fileName "padding-top: 0px;"
add-content $fileName "padding-right: 0px;"
add-content $fileName "padding-bottom: 0px;"
add-content $fileName "padding-left: 0px;"
add-content $fileName "}"
add-content $fileName "body {"
add-content $fileName "margin-left: 5px;"
add-content $fileName "margin-top: 5px;"
add-content $fileName "margin-right: 0px;"
add-content $fileName "margin-bottom: 10px;"
add-content $fileName ""
add-content $fileName "table {"
add-content $fileName "border: thin solid #000000;"
add-content $fileName "}"
add-content $fileName "-->"
add-content $fileName "</style>"
Add-Content $fileName "</head>"
Add-Content $fileName "<body>"
add-content $fileName "<table width='100%'>"
add-content $fileName "<tr bgcolor='#CCCCCC'>"
add-content $fileName "<td colspan='7' height='25' align='center'>"
add-content $fileName "<font face='tahoma' color='#003399' size='4'><strong> Server Health - $date</strong></font>"
add-content $fileName "</td>"
add-content $fileName "</tr>"
add-content $fileName "</table>"
}
# Function to write the HTML Header to the file
Function writeTableHeader
{
param($fileName)
Add-Content $fileName "<tr bgcolor=#CCCCCC>"
Add-Content $fileName "<td width='10%' align='center'>Name</td>"
Add-Content $fileName "<td width='50%' align='center'>ProcessId</td>"
Add-Content $fileName "<td width='10%' align='center'>State</td>"
Add-Content $fileName "<td width='10%' align='center'>StartMode</td>"
Add-Content $fileName "<td width='10%' align='center'>ExitCode</td>"
Add-Content $fileName "<td width='10%' align='center'>Status</td>"
Add-Content $fileName "</tr>"
}
Function writeHtmlFooter
{
param($fileName)
Add-Content $fileName "</body>"
Add-Content $fileName "</html>"
}
Function writeServiceInfo
{
param($fileName,$SvcName,$SvcPID,$SvcSM,$SvcExCd,$ServiceState,$SvcStatus)
$SvcName= $Item.Name
$SvcPID= $Item.ProcessId
$SvcSM= $Item.StartMode
$SvcExCd= $Item.ExitCode
$ServiceState= $Item.State
$SvcStatus= $Item.Status
#You can add multiple elseif statements if you wish to display certain events. I have server state of STOPPED in Red.
if ($ServiceState -eq $warning)
{
Add-Content $fileName "<tr>"
Add-Content $fileName "<td>$SvcName</td>"
Add-Content $fileName "<td>$SvcPID</td>"
Add-Content $fileName "<td bgcolor='#FF4C4C' align=center>$ServiceState</td>"
#FF4C4C RED #FBB917 ORANGE
Add-Content $fileName "<td>$SvcSM</td>"
Add-Content $fileName "<td>$SvcExCd</td>"
Add-Content $fileName "<td>$SvcStatus</td>"
Add-Content $fileName "</tr>"
}
else
{
Add-Content $fileName "<tr>"
Add-Content $fileName "<td>$SvcName</td>"
Add-Content $fileName "<td>$SvcPID</td>"
Add-Content $fileName "<td>$ServiceState</td>"
Add-Content $fileName "<td>$SvcSM</td>"
Add-Content $fileName "<td>$SvcExCd</td>"
Add-Content $fileName "<td>$SvcStatus</td>"
Add-Content $fileName "</tr>"
}
}
#The function for the sendemail at the end.
#Function sendEmail
#{ param($from,$to,$subject,$smtphost,$htmlFileName)
#$body = Get-Content $htmlFileName
#$smtp= New-Object System.Net.Mail.SmtpClient $smtphost
#$msg = New-Object System.Net.Mail.MailMessage $from, $to, $subject, $body
#$msg.isBodyhtml = $true
#$smtp.send($msg)
writeHtmlHeader $ServiceHealthFileName
foreach ($server in Get-Content $serverlist)
{
#This adds the Uptime for the server you will need $Display in your add-content.
$hostname = get-wmiobject win32_computersystem -computername $server | fl model
$os = Get-WmiObject win32_operatingsystem -ComputerName $server
$uptime = (Get-Date) - ($os.ConvertToDateTime($os.lastbootuptime))
$Display = "Uptime: " + $Uptime.Days + " days, " + $Uptime.Hours + " hours, " + $Uptime.Minutes + " minutes"
#This builds the header for each server and include the name and uptime.
Add-Content $ServiceHealthFileName "<table width='100%'><tbody>"
Add-Content $ServiceHealthFileName "<tr bgcolor='#CCCCCC'>"
Add-Content $ServiceHealthFileName "<td width='100%' align='center' colSpan=6><font face='tahoma' color='#003399' size='2'><strong> $server $Display </strong></font></td>"
Add-Content $ServiceHealthFileName "</tr>"
#This writes the header and builds the body of each server health
writeTableHeader $ServiceHealthFileName
$store = #()
$store += Get-WmiObject -Class Win32_Service -ComputerName $server -Filter "Name LIKE 'yourservice'"
$store += Get-WmiObject -Class Win32_Service -ComputerName $server -Filter "Name LIKE 'yourservice'"
$store += Get-WmiObject -Class Win32_Service -ComputerName $server -Filter "Name LIKE 'yourservice'"
$store += Get-WmiObject -Class Win32_Service -ComputerName $server -Filter "Name LIKE 'yourservice'"
$store += Get-WmiObject -Class Win32_Service -ComputerName $server -Filter "Name LIKE 'yourservice'"
$store += Get-WmiObject -Class Win32_Service -ComputerName $server -Filter "Name LIKE 'yourservice'"
$store += Get-WmiObject -Class Win32_Service -ComputerName $server -Filter "Name LIKE 'yourservice'"
$store += Get-WmiObject -Class Win32_Service -ComputerName $server -Filter "Name LIKE 'yourservice'"
#This write the body of each header in the order you defined
foreach ($item in $store)
{
#If you dont want on screen read out as the script progresses; comment out the write-host line.
#Write-Host $server $item.Name $item.ProcessId $item.State
writeServiceInfo $ServiceHealthFileName $item.Name $item.ProcessId $item.State $item.StartMode $Item.ExitCode $Item.Status
}
}
#This writes the footer
writeHtmlFooter $ServiceHealthFileName
$date = ( get-date ).ToString('yyyy/MM/dd')
#Use the below line to setup an email of the report,
#sendEmail emailaddress emailaddress "Server Status Report - $Date" EmailServer $ServiceHealthFileName
WMI Output All Services
If you don't mind using the built-in WMI output format, then this one-liner will accomplish exporting a listing of all services in table-format to HTML. If you needed this to run on multiple remote machines that can be accomplished with the /node: switch.
wmic /OUTPUT:%userprofile%\Desktop\%computername%_svc.html SERVICE list full /format:htable