Need some help in fixing PowerShell script to list servicename in HTML format & uptime in meaningful format ?

Hi All,

I wonder if anyone here can assist me in fixing the PowerShell script below:

#################################################################################################################################################################################
# Show the list of server in the specific OU that has problem with stopped service that is set to be running as Automatic when the CPU or the Memory load of the server is > 80% 
#################################################################################################################################################################################
#

$ResultFile = "C:\TEMP\TestResult.htm"
$StartOU = "OU=Production 1,OU=Computers,DC=MyDomain,DC=com"
$ServerList = @()
$ServerList = Get-ADComputer -Properties OperatingSystem, OperatingSystemVersion, lastLogonTimestamp, lastLogon -Filter {Enabled -eq $True} -SearchBase $StartOU |
				Where-Object {Test-Connection $_.Name -Count 1 -Quiet} | 
				Select-Object -Property Name

ForEach($Computer in $ServerList) {
    $hostdns = [System.Net.DNS]::GetHostEntry($Computer) 
    $OS = Get-WmiObject Win32_OperatingSystem -ComputerName $Computer -ErrorAction Stop
    $LastBoot = [System.Management.ManagementDateTimeconverter]::ToDateTime("$((Get-WmiObject Win32_OperatingSystem -ComputerName $Computer).LastBootUpTime)")
    $Uptime = (Get-Date) - $LastBoot
	
    $propHash = [ordered]@{ 
        ComputerName = $Computer 
        BootTime     = $BootTime 
        Uptime       = $Uptime 
    } 
    $objComputerUptime = New-Object PSOBject -Property $propHash 

$AVGProc = Get-WmiObject -ComputerName $computername win32_processor | Measure-Object -property LoadPercentage -Average | Select Average 
$OS = Get-WmiObject -Class -Class Win32_OperatingSystem -ComputerName $computername | Select-Object @{Name = "MemoryUsage"; Expression = {"{0:N2}" -f ((($_.TotalVisibleMemorySize - $_.FreePhysicalMemory)*100)/ $_.TotalVisibleMemorySize) }} 
$vol = Get-WmiObject -Class win32_Volume -ComputerName $computername -Filter "DriveLetter = 'C:'" | Select-object @{Name = "C PercentFree"; Expression = {"{0:N2}" -f  (($_.FreeSpace / $_.Capacity)*100) } } 
   
$result += [PSCustomObject] @{  
        ServerName = "$computername" 
        CPULoad = "$($AVGProc.Average)%" 
        MemLoad = "$($OS.MemoryUsage)%" 
        CDrive = "$($vol.'C PercentFree')%" 
} 

 $Service = Get-WmiObject Win32_Service -ComputerName $computername | Where {($_.startmode -like "*auto*") -and ($_.state -notlike "*running*")} |` 
	            foreach { new-object psobject -Property @{
		                                    DisplayName = $_.DisplayName
		                                    Name = $_.Name
		                                    StartMode = $_.StartMode
		                                    State = $_.State
	                                    }
	            }

    $Outputreport = "<HTML><TITLE> Server Health Report </TITLE> 
                     <BODY background-color:peachpuff> 
                     <font color =""#99000"" face=""Microsoft Tai le""> 
                     <H2> Server Health Report </H2></font> 
                     <Table border=1 cellpadding=0 cellspacing=0> 
                     <TR bgcolor=gray align=center>
                      <TD><B>Server Name</B></TD> 
                      <TD><B>Uptime</B></TD>  
                       <TD><B>C Drive Utilizatoin</B></TD>
                       <TD><B>Service Displayname</B></TD>
                       <TD><B>Service Name</B></TD>
                       <TD><B>StartMode</B></TD>
                       <TD><B>State</B></TD>
                       </TR>" 
                         
    Foreach($Entry in $Result) {  
          if((($Entry.CpuLoad) -or ($Entry.memload)) -ge "80") {  
            $Outputreport += "<TR bgcolor=red>"  
          }  
          else { 
            $Outputreport += "<TR>"  
          } 
          $Outputreport += "<TD>$($Entry.Servername)</TD><TD>$($objComputerUptime.Uptime)</TD><TD align=center>$($Entry.Cdrive)</TD>
          <TD>$($Service.DisplayName)</TD><TD>$($Service.Name)</TD><TD>$($Service.StartMode)</TD><TD>$($Service.State)</TD>
          </TR>"  
        } 
     $Outputreport += "</Table></BODY></HTML>"  
}  

$Outputreport | out-file $ResultFile -NoClobber
Invoke-Expression $ResultFile 

Open in new window


Problem:
1. I cannot display the Uptime in the meaningful format like Days, Hours...
2. I cannot display the service name in the proper HTML table for easy reading.

Thanks in advance.
LVL 9
Senior IT System EngineerIT ProfessionalAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

yo_beeDirector of Information TechnologyCommented:
Can you post an example of how you want the update to look like?

Are you going to create one large HTML Table of all your servers?  I ran this against my computer only and it is very difficult to read.

Does your output file look like mine?
TestResult.htm
0
Senior IT System EngineerIT ProfessionalAuthor Commented:
Hi Yo_Bee,
This is my sample output.Screenshot
This is the expected Output that I'd like to know:
Expected result
0
Dorababu MSenior Software EngineerCommented:
If you are good at html you can loop through and display them in particualr td and tr

foreach($s in $Service)
{
       $s.DisplayName
       $s.Name
}

Open in new window

1
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Dorababu MSenior Software EngineerCommented:
A sample change it as per your need

 $Outputreport = "<HTML><TITLE> Server Health Report </TITLE> 
                     <BODY background-color:peachpuff> 
                     <font color =""#99000"" face=""Microsoft Tai le""> 
                     <H2> Server Health Report </H2></font> 
                     <Table border=1 cellpadding=0 cellspacing=0> 
                     <TR bgcolor=gray align=center>
                      
                       <TD ><B>Service Displayname</B></TD>
                       <TD ><B>Service Name</B></TD>
                       <TD ><B>StartMode</B></TD>
                       <TD ><B>State</B></TD>
                       </TR>" 

 $Service = Get-WmiObject Win32_Service -ComputerName $env:COMPUTERNAME |` 
    where     {($_.startmode -like "*auto*") -and ` 
            ($_.state -notlike "*running*")}|` 
            foreach {
   new-object psobject -Property @{
                                    DisplayName = $_.DisplayName
                                    Name = $_.Name
                                    StartMode = $_.StartMode
                                    State = $_.State
                                    }
                                    }

                                    foreach($s in $Service)
                                    {
                                        $Outputreport += "<TR><TD>$($s.DisplayName)</TD><TD>$($s.Name)</TD><TD>$($s.StartMode)</TD><TD>$($s.State)</TD>"
                                    }
                                    $Outputreport += "</Table></BODY></HTML>"  
                                    $Outputreport | out-file C:\Test.htm  
Invoke-Expression C:\Test.htm 

Open in new window

1
Shaun VermaakTechnical Specialist/DeveloperCommented:
1
oBdACommented:
This should do the trick:
#################################################################################################################################################################################
# Show the list of server in the specific OU that has problem with stopped service that is set to be running as Automatic when the CPU or the Memory load of the server is > 80% 
#################################################################################################################################################################################

$ResultFile = "C:\TEMP\TestResult.htm"
$StartOU = "OU=Production 1,OU=Computers,DC=MyDomain,DC=com"
Write-Host "Generating server list ..."
$ServerList = Get-ADComputer -Filter {Enabled -eq $True} -SearchBase $StartOU | Where-Object {Test-Connection $_.Name -Count 1 -Quiet} | Select-Object -ExpandProperty Name

$CriticalCpu = 80
$CriticalMem = 80
$Title = 'Server Health Report'
$UptimeFormat = "dd' Days 'hh' Hours 'mm' Minutes'"
$HtmlHead = @'
<style>
	body				{background-color:peachpuff;}
	table				{border-width:1px; border-style:solid; border-color:black; border-collapse:collapse;}
	th					{border-width:1px; border-style:solid; border-color:black; padding:1px; background-color:gray; text-align:center;}
	td					{border-width:1px; border-style:solid; border-color:black; padding:1px;}
	tr					{text-align:center;}
	tr[Critical="True"]	{background-color: red;}
</style>
'@

$ServerList | ForEach-Object {
	Write-Host "Processing $($_) ..."
	$Row = '' | Select-Object 'Server Name', 'Uptime', 'C Drive Free %', 'Service DisplayName', 'Service Name', 'CPU Load %', 'Memory Usage %'
	$Row.'Server Name' = $_
	Try {
		$OS = Get-WmiObject -Query "Select FreePhysicalMemory, LastBootUpTime, TotalVisibleMemorySize From Win32_OperatingSystem" -ComputerName $_ -ErrorAction Stop
		$VolC = Get-WmiObject -Query "Select Capacity, FreeSpace From Win32_Volume Where (DriveLetter = 'C:')" -ComputerName $_ -ErrorAction Stop
		$Services = Get-WmiObject -Query "Select DisplayName, Name From Win32_Service Where (StartMode='Auto') And (State!='Running')" -ComputerName $_ -ErrorAction Stop
		$CPU = Get-WmiObject -Query "Select LoadPercentage From Win32_Processor" -ComputerName $_ -ErrorAction Stop
		$Row.'Uptime' = ((Get-Date) - [System.Management.ManagementDateTimeconverter]::ToDateTime($OS.LastBootUpTime)).ToString($UptimeFormat)
		$Row.'C Drive Free %' = [Math]::Round((100 * $VolC.FreeSpace / $VolC.Capacity), 2).ToString([cultureinfo]::GetCultureInfo('en-US'))
		$Row.'Service DisplayName' = ($Services | Select-Object -ExpandProperty DisplayName) -join "@CRLF@"
		$Row.'Service Name' = ($Services | Select-Object -ExpandProperty Name) -join "@CRLF@"
		$Row.'CPU Load %' = $CPU | Measure-Object -Property LoadPercentage -Average | Select-Object -ExpandProperty Average
		$Row.'Memory Usage %' = [Math]::Round(((($OS.TotalVisibleMemorySize - $OS.FreePhysicalMemory) * 100) / $OS.TotalVisibleMemorySize), 2).ToString([cultureinfo]::GetCultureInfo('en-US'))
		$Row
	} Catch {
		Write-Error $_
	}
} | ConvertTo-Html -Head $HtmlHead -PreContent "<H2>$($Title)</H2>" |
	ForEach-Object {$_.Replace('@CRLF@', "<br />")} |
	ForEach-Object {
		If ($_ -match '\A<tr><td>') {
			$_ -replace '<tr>', "<tr Critical=`"$(([int]([xml]$_).SelectSingleNode('/tr/td[6]').InnerText -gt $CriticalCpu) -or ([int]([xml]$_).SelectSingleNode('/tr/td[7]').InnerText -gt $CriticalMem))`">"
		} Else {
			$_
		}
	} |
	Set-Content -Path $ResultFile

Invoke-Expression $ResultFile

Open in new window

1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Senior IT System EngineerIT ProfessionalAuthor Commented:
Thanks all for participating in this question.
OBDA has fixed it fully working :-)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.