Assistance with Powershell script for gathering RAM/CPU/HDD/process information

Hello powershell.org,

I’ve used this site a few times in the past but just now in a position to need to make a post. I’ll start off and say I’m not a developer and haven’t done much in the way of scripting in the last 15 years, so please bear that in mind. I’m a network engineer and machinist/mechanic so I’m much more familiar with the hands-on parts of IT.

With that out of the way, my boss has assigned me the task of generating a powershell script that will gather:

Current CPU, RAM, and disk usage
List of current processes and CPU/RAM used by each
Export this information to a CSV file

Below is what I have so far. It… sort of works. I’ll admit, 0% of this is my own work. It’s all stuff I’ve gathered from various sources on Google and tinkered with to try to make the CSV export work. The exported file has a lot of random junk in it that I don’t know how to get rid of. The last section is commented out at the moment, that’s another attempt at the process CPU/RAM usage that I was messing with but I couldn’t make it work either. At this point, I’ve spent 4.5 hours on this. I feel like someone that knows what they’re doing could definitely have finished this 5 times over in that time.

If anyone could please help make this work I would be very grateful.

[pre]$outfile = ‘C:\dump.csv’
if (Get-ChildItem $outfile) {
(Get-ChildItem $outfile).Delete()
}
#Get CPU usage
$CpuLoad = (Get-WmiObject win32_processor | Measure-Object -property LoadPercentage -Average | Select Average )| ConvertTo-Csv | Out-File $outfile -Append

#Get RAM usage
Get-Counter ‘\Memory\Available MBytes’ | ConvertTo-Csv | Out-File $outfile -Append

#Get HDD usage
Get-PSDrive | ConvertTo-Csv | Out-File $outfile -Append

#Processes with RAM and CPU usage
Get-WmiObject Win32_PerfFormattedData_PerfProc_Process | Where-Object { $_.name -inotmatch '_total|idle' }
| ForEach-Object {
“Process={0,-25} CPU_Usage={1,-12} Memory_Usage_(MB)={2,-16}” -f `
$.Name,$.PercentProcessorTime,([math]::Round($_.WorkingSetPrivate/1Mb,2))
} | ConvertTo-Csv | Out-File $outfile -Append

#Get-Counter ‘\Process(*)% Processor Time’ `

| Select-Object -ExpandProperty countersamples `

| Select-Object -Property instancename, cookedvalue `

| Sort-Object -Property cookedvalue -Descending | Select-Object -First 20 `

| select InstanceName,@{L=‘CPU’;E={($_.Cookedvalue/100).toString(‘P’)}} | ConvertTo-Csv | Out-File $outfile -Append[/pre]

Hi OldGreyBeast85,

I’ve never tried to get cpu & memory usage. Just cpu & men config.

Instead of get-psdrive for disk, try get-volume

 

I just tried that, but I get no return into the CSV with get-volume. The process CPU/Mem usage doesn’t seem to export to CSV either.

Start by searching on “powershell server inventory report”. Most of the items you have asked for has been done many times, this would be on example:

https://4sysops.com/archives/how-to-build-a-powershell-inventory-script-for-windows-servers/

One of the first things I’ll recommend is that CSV is not a good method of viewing these reports. A csv is a flat file, most of the information you’re collecting is a collection of information. For example, you have one to one data for CPU, Memory, the computer name, however, disks could be one or many. If you think of it as simple tables or a sheet in Excel, the disk would need their own sheet with a header and multiple rows as would processes. Most of these reports are HTML as it gives much more flexibility in how the data is conveyed (you can even use corporate colors, logos, etc. to make them spiffy), so take a look at this:

Creating HTML Reports in Windows PowerShell

Here is some of the code you posted cleaned up a bit if it’s still required if you cannot find it in a report that’s built:

#Get CPU usage
Get-WmiObject win32_processor | Measure-Object -property LoadPercentage -Average | Select Average

#Get RAM usage
Get-Counter ‘\Memory\Available MBytes’ | Select -ExpandProperty CounterSamples | Select @{Name='Mem_Avail_(MB)';Expression={$_.CookedValue}}

#Get HDD usage
Get-PSDrive -PSProvider FileSystem

#Processes with RAM and CPU usage
Get-WmiObject Win32_PerfFormattedData_PerfProc_Process -Filter "NOT Name LIKE 'svchost%' AND NOT Name LIKE 'chrome%'" | 
Select-Object -Property @{Name='Process';Expression={$_.Name}},
                        @{Name='CPU_Usage';Expression={$_.PercentProcessorTime}},
                        @{Name='Memory_Usage_(MB)';Expression={[math]::Round($_.WorkingSetPrivate/1Mb,2)}}


Thank you Rob, unfortunately the CSV requirement is a mandate by my boss, so I can’t use any of the HTML formatted reports that are available (and I’m not saavy enough to modify those to CSV). I will try the new code and see if that will work when I’ve got some time tomorrow. Stuck on a phone call at the moment.

Rob,

I tried running your cleaned up code, but the only value I see returned is the Average CPU usage. It looks like the other functions aren’t working. Also, as I said in the last reply it has to be exported to a CSV per my boss, anything other than CSV will not work.

I read through the link you provided but it provided things like total memory instead of used memory. I haven’t been able to find an inventory report deal that focuses on server utilization rather than just finding the specs of the server, which we already gather via other means.

Not sure why when you run that as a block it doesn’t work, odd. If you run the commands individually they show in the console. Anywho, regardless of you feeling that a CSV is a mandate, simply gluing together a bunch of CSV’s into a single file does not make it a CSV. CSV’s are great as you typically can open them in Excel and filter and format them, what you are doing is NOT in CSV format, it’s just a bunch of data jammed into a file:

$csv = @()
#Get CPU usage
$csv += Get-WmiObject win32_processor | Measure-Object -property LoadPercentage -Average | Select Average | ConvertTo-Csv -NoTypeInformation

#Get RAM usage
$csv += Get-Counter ‘\Memory\Available MBytes’ | Select -ExpandProperty CounterSamples | Select @{Name='Mem_Avail_(MB)';Expression={$_.CookedValue}} | ConvertTo-Csv -NoTypeInformation

#Get HDD usage
$csv += Get-PSDrive -PSProvider FileSystem | ConvertTo-Csv -NoTypeInformation

#Processes with RAM and CPU usage
$csv += Get-WmiObject Win32_PerfFormattedData_PerfProc_Process -Filter "NOT Name LIKE 'svchost%' AND NOT Name LIKE 'chrome%'" | 
Select-Object -Property @{Name='Process';Expression={$_.Name}},
                        @{Name='CPU_Usage';Expression={$_.PercentProcessorTime}},
                        @{Name='Memory_Usage_(MB)';Expression={[math]::Round($_.WorkingSetPrivate/1Mb,2)}} |
ConvertTo-Csv -NoTypeInformation

$finalCSV = $csv -join "nr"

$finalCSV | Out-File -FilePath C:\Scripts\test.csv

Unusable Output:

"Average"
"4"
"Mem_Avail_(MB)"
"6351"
"Used","Free","CurrentLocation","Name","Provider","Root","Description","MaximumSize","Credential","DisplayRoot"
"222586507264","288184295424","WINDOWS\system32","C","Microsoft.PowerShell.Core\FileSystem","C:\","Windows-SSD",,"System.Management.Automation.PSCredential",
"Process","CPU_Usage","Memory_Usage_(MB)"
"1Password","0","1.67"
"1Password#1","0","6.3"
"ApplicationFrameHost","0","3.48"
"AuthManSvr","0","1.5"
"Box Edit","0","4.58"
"Box Local Com Service","0","3.35"
"CtxWebBrowser","0","2.37"
"CtxWebBrowser#1","0","2.3"
"DAX3API","0","8.85"
"DbxSvc","0","1.26"
"Dropbox","0","80.14"
"Dropbox#1","0","0.52"
"Dropbox#2","0","1.07"
"DropboxUpdate","0","0.37"
"EvtEng","0","1.95"
"FMService64","0","0.41"
"FoxitProxyServer_Socket_RD","0","0.35"
"GoogleCrashHandler","0","0.33"
"GoogleCrashHandler64","0","0.3"
"HostAppServiceUpdater","0","0.75"
"Idle","682","0.01"
"IntelAudioService","0","2.09"
...

Strongly suggest you look a the HTML route as it’s made to create reports. Email supports HTML body, so it can be emailed with Send-MailMessage.

Perfect! I don’t think I could have ever gotten this working without your help. I’ve run this on a customer server and sent the data to my boss to see if that works for whatever process he has planned for it.

I will clarify one thing though… I don’t “feel” that CSV is a mandate, it just is one. My boss says “give me this in CSV” so I don’t have the option to give him something else. He will say “this is wrong do it again like I said to do it.” I totally agree with you that the CSV output looks totally unusable, but that’s what he wants so I assume he’s got some plan on doing something with it.

Again, thank you so much. I burned so many hours trying to make this work and was just beating my head against the wall in frustration.