jack jones
asked on
How to add Avg CPU and Memory utilization, C disk utilization- Powershell
Im using script to get the uptime of list of servers.. How to add 3 more columns to show Avg CPU, Memory utilization and C disk utilization using powershell
CLS
Write-Host "One moment please... Setting up..."
$ServerNameOption = "File"
$ServerNameFile = "C:\ttt.txt"
$BGColorColumn = "#BFC3C4"
$BGColorOnline = "#6DC046"
$BGColorOffline = "#D43235"
$BGColorReportTotal = "#4AA7E1"
$SendEmail = "True"
$ShowOnScreen = "False"
$ShowHTMLOnScreen = "False"
$ReportOutFile = "D:\test.html"
<#==============================
SMTP Settings
Edit with your email settings:
================================#>
$smtpsettings = @{
To = "receiver"
From = "Sender"
Subject = "Server Report for $(Get-Date -Format D)"
SmtpServer = "smtp"
}
<#========
Counters
==========#>
$ServerCount = 0
$SuccessCount = 0
$UnreachableCount = 0
<#====================
HTML Report Settings
======================#>
$Report = "
<html>
<head>
<title> ServerReport </title>
</head>
<body {background-color:#D7D8D8;}>
<H1 Align=`"Center`"> <B>Report </B></H1>
<H3 Align=`"Center`"> $(Get-Date -Format D) </H3>
<H3 Align=`"Center`"> $(Get-Date -Format T) </H3>
<table Border=`"1`" CellPadding=`"3`" Align=`"Center`">
<tr>
<td BGColor=$BGColorColumn Align=center><b> SERVER NAME </b></td>
<td BGColor=$BGColorColumn Align=center><b> STATUS </b></td>
<td BGColor=$BGColorColumn Align=center><b> UPTIME </b></td>
<td BGColor=$BGColorColumn Align=center><b> Avrg.CPU Utilization </b></td>
<td BGColor=$BGColorColumn Align=center><b> Memory Utilization </b></td>
<td BGColor=$BGColorColumn Align=center><b> C Drive Utilizatoin </b></td>
</tr>"
<#========================
Query servers for uptime
==========================#>
IF ($ShowOnScreen -eq "True")
{
Write-Host
Write-Host "Server querying initiated."
}
IF ($ServerNameOption -eq "File")
{
Write-Host
Write-Host "Reading server names from file:" $ServerNameFile
$ServerName = Get-Content -Path $ServerNameFile | Sort
}
Else
{
<# Write-Host
Write-Host "Reading server names from Active Directory."
Write-Host "One moment please..."
$ServerName = (Get-ADComputer -Filter { OperatingSystem -like '*Server*'} -Properties *).name | Sort #>
}
IF ($ShowOnScreen -eq "True")
{
CLS
Write-Host "Server Uptime Report"
Write-Host $(Get-Date -Format D)
Write-Host $(Get-Date -Format T)
}
ForEach($Server in $ServerName) {
$OutputObj = New-Object -TypeName PSobject
$OutputObj | Add-Member -MemberType NoteProperty -Name ServerName -Value $Server
$Status = 0
$ServerCount++
If(Test-Connection -Computer $Server -count 1 -ea 0) {
$OutputObj | Add-Member -MemberType NoteProperty -Name Status -Value "Online"
try {
$BootTime = (Get-WmiObject win32_operatingSystem -computer $Server -ErrorAction stop).lastbootuptime
$BootTime = [System.Management.ManagementDateTimeconverter]::ToDateTime($BootTime)
$Now = Get-Date
$span = New-TimeSpan $BootTime $Now
$Days = $span.days
$Hours = $span.hours
$Minutes = $span.minutes
$Seconds = $span.seconds
<#===============================
Remove plurals if the value = 1
=================================#>
If ($Days -eq 1)
{$Day = "1 day "}
else
{$Day = "$Days days "}
If ($Hours -eq 1)
{$Hr = "1 hr "}
else
{$Hr = "$Hours hrs "}
If ($Minutes -eq 1)
{$Min = "1 min "}
else
{$Min = "$Minutes mins "}
If ($Seconds -eq 1)
{$Sec = "1 sec"}
else
{$Sec = "$Seconds secs"}
$Uptime = $Day + $Hr + $Min + $Sec
<#==================
Create Output List
====================#>
$OutputObj | Add-Member -MemberType NoteProperty -Name Uptime -Value $Uptime
$Status=1
$SuccessCount++
} catch {
$OutputObj | Add-Member -MemberType NoteProperty -Name Uptime -Value "Query Failed"
<# Not currently reporting on this... #>
}
} else {
$OutputObj | Add-Member -MemberType NoteProperty -Name Status -Value "Offline"
$OutputObj | Add-Member -MemberType NoteProperty -Name Uptime -Value "Unreachable"
$UnreachableCount++
}
<#===============================================
Display output on screen and add to HTML report
=================================================#>
IF ($ShowOnScreen -eq "True")
{
$OutputObj
}
If($Status) {
$BGColor=$BGColorOnline
} else {
$BGColor=$BGColorOffline
}
$Report += "
<TR>
<TD BGColor=$BGColor Align = center>$($OutputObj.ServerName)</TD>
<TD BGColor=$BGColor Align = center>$($OutputObj.Status)</TD>
<TD BGColor=$BGColor Align = center>$($OutputObj.Uptime)</TD>
</TR>"
}
<#====================
Assemble HTML Report
======================#>
$Report +="
</table>
<br>
<table Border=`"1`" CellPadding=`"3`" Align=`"Center`">
<tr>
<td BGColor=$BGColorReportTotal Align = right>Servers Scanned: </td>
<td BGColor=$BGColorReportTotal Align = right>$ServerCount</td>
</tr>
<tr>
<td BGColor=$BGColorOnline Align = right>Servers Online: </td>
<td BGColor=$BGColorOnline Align = right>$SuccessCount</td>
</tr>
<tr>
<td BGColor=$BGColorOffline Align = right>Servers Offline: </td>
<td BGColor=$BGColorOffline Align = right>$UnreachableCount</td>
</tr>
</table>
</body>
</html>"
#$Report | Out-File $ReportOutFile -Force
<#==============================================================================================================
Show HTML report on screen
==============================================================================================================#>
IF ($ShowHTMLOnScreen -eq "True")
{
Invoke-Item $ReportOutFile
}
<#==============================================================================================================
Email HTML Report
==============================================================================================================#>
IF ($SendEmail -eq "True")
{
Send-MailMessage @smtpsettings -Body $Report -BodyAsHtml
}
IF ($ShowOnScreen -eq "True")
{
Write-Host
Write-Host
Write-Host "Completed."
Read-Host -Prompt "Press the [ENTER] key to exit..."
}
ASKER
The script gives the same output it gives blank in other 3 columns of cpu, mem , c drive.
.error
I have the logic we just need to integrate into it, can we do this
.error
Get-Counter : Unable to connect to the specified computer or the computer is offline.
At line:110 char:16
+ $Perfcount = Get-Counter -computer $Server -Counter "\memory\available mbytes ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidResult: (:) [Get-Counter], Exception
+ FullyQualifiedErrorId : CounterApiError,Microsoft.PowerShell.Commands.GetCounterCommand
I have the logic we just need to integrate into it, can we do this
$AVGProc = Get-WmiObject -computername $computername win32_processor |
Measure-Object -property LoadPercentage -Average | Select Average
$OS = gwmi -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) } }
Hi
Please try the following
Please try the following
CLS
Write-Host "One moment please... Setting up..."
$ServerNameOption = "File"
$ServerNameFile = "C:\ttt.txt"
$BGColorColumn = "#BFC3C4"
$BGColorOnline = "#6DC046"
$BGColorOffline = "#D43235"
$BGColorReportTotal = "#4AA7E1"
$SendEmail = "True"
$ShowOnScreen = "False"
$ShowHTMLOnScreen = "False"
$ReportOutFile = "D:\test.html"
<#==============================
SMTP Settings
Edit with your email settings:
================================#>
$smtpsettings = @{
To = "receiver"
From = "Sender"
Subject = "Server Report for $(Get-Date -Format D)"
SmtpServer = "smtp"
}
<#========
Counters
==========#>
$ServerCount = 0
$SuccessCount = 0
$UnreachableCount = 0
<#====================
HTML Report Settings
======================#>
$Report = "
<html>
<head>
<title> ServerReport </title>
</head>
<body {background-color:#D7D8D8;}>
<H1 Align=`"Center`"> <B>Report </B></H1>
<H3 Align=`"Center`"> $(Get-Date -Format D) </H3>
<H3 Align=`"Center`"> $(Get-Date -Format T) </H3>
<table Border=`"1`" CellPadding=`"3`" Align=`"Center`">
<tr>
<td BGColor=$BGColorColumn Align=center><b> SERVER NAME </b></td>
<td BGColor=$BGColorColumn Align=center><b> STATUS </b></td>
<td BGColor=$BGColorColumn Align=center><b> UPTIME </b></td>
<td BGColor=$BGColorColumn Align=center><b> Avrg.CPU Utilization </b></td>
<td BGColor=$BGColorColumn Align=center><b> Memory Utilization </b></td>
<td BGColor=$BGColorColumn Align=center><b> C Drive Utilizatoin </b></td>
</tr>"
<#========================
Query servers for uptime
==========================#>
IF ($ShowOnScreen -eq "True")
{
Write-Host
Write-Host "Server querying initiated."
}
IF ($ServerNameOption -eq "File")
{
Write-Host
Write-Host "Reading server names from file:" $ServerNameFile
$ServerName = Get-Content -Path $ServerNameFile | Sort
}
Else
{
<# Write-Host
Write-Host "Reading server names from Active Directory."
Write-Host "One moment please..."
$ServerName = (Get-ADComputer -Filter { OperatingSystem -like '*Server*'} -Properties *).name | Sort #>
}
IF ($ShowOnScreen -eq "True")
{
CLS
Write-Host "Server Uptime Report"
Write-Host $(Get-Date -Format D)
Write-Host $(Get-Date -Format T)
}
ForEach($Server in $ServerName) {
$OutputObj = New-Object -TypeName PSobject
$OutputObj | Add-Member -MemberType NoteProperty -Name ServerName -Value $Server
$Status = 0
$ServerCount++
If(Test-Connection -Computer $Server -count 1 -ea 0) {
$OutputObj | Add-Member -MemberType NoteProperty -Name Status -Value "Online"
try {
$BootTime = (Get-WmiObject win32_operatingSystem -computer $Server -ErrorAction stop).lastbootuptime
$BootTime = [System.Management.ManagementDateTimeconverter]::ToDateTime($BootTime)
$Now = Get-Date
$span = New-TimeSpan $BootTime $Now
$Days = $span.days
$Hours = $span.hours
$Minutes = $span.minutes
$Seconds = $span.seconds
$Perfcount = Get-Counter -computer $Server -Counter "\memory\available mbytes","\processor(_total)\% processor time","\LogicalDisk(C:)\Free Megabytes" -MaxSamples 10 -SampleInterval 1
$memory = (($Perfcount.countersamples | group path )[0].group.cookedvalue | measure -Average).average
$cpu = (($Perfcount.countersamples | group path )[1].group.cookedvalue | measure -Average).average
$disk = (($Perfcount.countersamples | group path )[2].group.cookedvalue | measure -Average).average
$AVGProc = Get-WmiObject -computername $server win32_processor | Measure-Object -property LoadPercentage -Average | Select Average
$OS = gwmi -Class win32_operatingsystem -computername $server | Select-Object @{Name = "MemoryUsage"; Expression = {“{0:N2}” -f ((($_.TotalVisibleMemorySize - $_.FreePhysicalMemory)*100)/ $_.TotalVisibleMemorySize) }}
$vol = Get-WmiObject -Class win32_Volume -ComputerName $server -Filter "DriveLetter = 'C:'" |Select-object @{Name = "C PercentFree"; Expression = {“{0:N2}” -f (($_.FreeSpace / $_.Capacity)*100) } }
<#===============================
Remove plurals if the value = 1
=================================#>
If ($Days -eq 1)
{$Day = "1 day "}
else
{$Day = "$Days days "}
If ($Hours -eq 1)
{$Hr = "1 hr "}
else
{$Hr = "$Hours hrs "}
If ($Minutes -eq 1)
{$Min = "1 min "}
else
{$Min = "$Minutes mins "}
If ($Seconds -eq 1)
{$Sec = "1 sec"}
else
{$Sec = "$Seconds secs"}
$Uptime = $Day + $Hr + $Min + $Sec
<#==================
Create Output List
====================#>
$OutputObj | Add-Member -MemberType NoteProperty -Name Uptime -Value $Uptime
#$OutputObj | Add-Member -MemberType NoteProperty -Name CPU -Value $CPU
#$OutputObj | Add-Member -MemberType NoteProperty -Name "Available Memory(Mb)" -Value $memory
#$OutputObj | Add-Member -MemberType NoteProperty -Name "AVGProc" -Value $AVGProc
$OutputObj | Add-Member -MemberType NoteProperty -Name " Free Space" -Value $disk
$OutputObj | Add-Member -MemberType NoteProperty -Name "Memory Usage" -Value $os
$OutputObj | Add-Member -MemberType NoteProperty -Name "Free Space" -Value $vol
$Status=1
$SuccessCount++
} catch {
$OutputObj | Add-Member -MemberType NoteProperty -Name Uptime -Value "Query Failed"
<# Not currently reporting on this... #>
}
} else {
$OutputObj | Add-Member -MemberType NoteProperty -Name Status -Value "Offline"
$OutputObj | Add-Member -MemberType NoteProperty -Name Uptime -Value "Unreachable"
$UnreachableCount++
}
<#===============================================
Display output on screen and add to HTML report
=================================================#>
IF ($ShowOnScreen -eq "True")
{
$OutputObj
}
If($Status) {
$BGColor=$BGColorOnline
} else {
$BGColor=$BGColorOffline
}
$Report += "
<TR>
<TD BGColor=$BGColor Align = center>$($OutputObj.ServerName)</TD>
<TD BGColor=$BGColor Align = center>$($OutputObj.Status)</TD>
<TD BGColor=$BGColor Align = center>$($OutputObj.Uptime)</TD>
</TR>"
}
<#====================
Assemble HTML Report
======================#>
$Report +="
</table>
<br>
<table Border=`"1`" CellPadding=`"3`" Align=`"Center`">
<tr>
<td BGColor=$BGColorReportTotal Align = right>Servers Scanned: </td>
<td BGColor=$BGColorReportTotal Align = right>$ServerCount</td>
</tr>
<tr>
<td BGColor=$BGColorOnline Align = right>Servers Online: </td>
<td BGColor=$BGColorOnline Align = right>$SuccessCount</td>
</tr>
<tr>
<td BGColor=$BGColorOffline Align = right>Servers Offline: </td>
<td BGColor=$BGColorOffline Align = right>$UnreachableCount</td>
</tr>
</table>
</body>
</html>"
#$Report | Out-File $ReportOutFile -Force
<#==============================================================================================================
Show HTML report on screen
==============================================================================================================#>
IF ($ShowHTMLOnScreen -eq "True")
{
Invoke-Item $ReportOutFile
}
<#==============================================================================================================
Email HTML Report
==============================================================================================================#>
IF ($SendEmail -eq "True")
{
Send-MailMessage @smtpsettings -Body $Report -BodyAsHtml
}
IF ($ShowOnScreen -eq "True")
{
Write-Host
Write-Host
Write-Host "Completed."
Read-Host -Prompt "Press the [ENTER] key to exit..."
}
###############################################
ASKER
Hi Joe
I still get the below error. And columns for cpu mem disk still appears to be blan .. :(
I still get the below error. And columns for cpu mem disk still appears to be blan .. :(
Get-Counter : Unable to connect to the specified computer or the computer is offline.
At line:110 char:16
+ $Perfcount = Get-Counter -computer $Server -Counter "\memory\available mbytes ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidResult: (:) [Get-Counter], Exception
+ FullyQualifiedErrorId : CounterApiError,Microsoft.PowerShell.Commands.GetCounterCommand
Capturetest.PNG
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Hi Joe yes it worked. Thanks .. What was the issue and resolution
Just need to confirm for C Drive utilization what it returns the total space left or percent of total space left or something else
Just need to confirm for C Drive utilization what it returns the total space left or percent of total space left or something else
The key problem was that I had forgot to add the details into the html tables so I added lines 188-190. As for the C Drive utilization this is calculated on line 116 an returns % free
I have been able to test but this should do the trick.
code added lines 110 -114 and 144-146
Open in new window