Saturday, October 25, 2014

Capture top memory consuming task manager processes with Powershell

One of x-colleague and good friend of mine called me and said that, recently they are receiving lots of alerts for high memory usage on their monitoring software (Windows and Linux), As they are using some old open source tool currently and it doesn't have capability to tell which process is consuming most of the memory. (It can be monitored through Performance Monitor - Perfmon under Process, This script is just created out of curiosity)

He asked me to write a script to capture top 10 memory consuming processes (for Windows servers) in CSV/XLS file format for creating fancy charts. (Another request was that He should be able to schedule it as they were receiving alerts randomly any time of day or after couple of days for few minutes only, keep watching task manager or resource monitor whole day was very time consuming process and not good for them when meeting SLAs)

below script is useful for the same conditions or can be used as general purpose tool by system administrators.

   <#  
   .SYNOPSIS  
   PowerShell function to monitor what process is using resources   
   .DESCRIPTION  
   Includes parameters to monitor server and latecy, and capture data in file.  
   .EXAMPLE  
   Monitor-ProcessMemoryUsage -IntervalinSeconds 600 -MonitorPeriodHours 1 -File c:\temp\CapturedData.csv  
   #>   
  #####################################   
  ## http://kunaludapi.blogspot.com   
  ## Version: 1   
  ## Tested this script on successfully  
  ## 1) Powershell v4   
  ## 2) Windows 7   
  ##   
  #####################################  
   [CmdletBinding()]  
     param(  
       [Parameter(Mandatory=$False, HelpMessage="Enter Interval in seconds[After how many second you want to capture data]")]  
       [alias("Interval","I")]  
       [string]$IntervalinSeconds = 300,  
       [Parameter(Mandatory=$False, HelpMessage="For how long you want to capture data [in hours]")]  
       [alias("Monitor","M")]  
       [string]$MonitorPeriodHours = 1,  
       [Parameter(Mandatory=$False, HelpMessage="Where you want to store CSV file")]  
       [alias("File","F")]  
       [string]$FileName = "$env:USERPROFILE\Desktop\$("MemUsage{0}{1}{2}.csv" -f $(Get-Date).day, $(Get-Date).Month, $(Get-Date).Year)"  
     )  
   begin {  
     $FutureTime = [DateTime]::Now.AddHours($MonitorPeriodHours)  
     $i=0  
   }  
   process {  
     do {  
       $i++  
       $TimeNow = [DateTime]::Now  
       $AllProcesses = Get-Process -IncludeUserName   
       $Processors = Get-WmiObject -Namespace root\CIMv2 -Class win32_processor | Select-Object -ExpandProperty NumberOfLogicalProcessors  
       $SortedMemory = $AllProcesses | Sort-Object PM -Descending   
       $TopMemory = $SortedMemory | Select-Object -First 10 -Property @{l="Number"; e={$i}}, @{l="Time"; e={$TimeNow}}, Name, Description, Path, Id, StartTime, @{l="Private Memory (MB)"; e={[Math]::Round($($_.PM / 1mb),2)}}, UserName  
       $TopMemory | Export-Csv -NoTypeInformation -Path $FileName -Append  
       Start-Sleep -Seconds $IntervalinSeconds  
     }   
     While ([DateTime]::Now -lt $FutureTime)  
   }  
   end {}  

How does this script works?
Get-Process is the the main cmdlet will pull the required data. You will have to copy paste script in notepad and save it as ps1 extension file. In my scenario I named it Monitor-ProcessMemoryUsage.ps1 and saved it in c:\temp folder location

Open powershell (run as administrator), change directory path to the location where ps1, script is stored 



and run the the ps1 file as above screenshot, there are some of the parameters associated (if you dont provide any parameters and just run the script with .\monitor-processmemoryusage.ps1 it will take below values by default)


-IntervalinSeconds

After how many seconds you want to monitor and store process memory usage in file., if you dont provide this value it will take 300 seconds means after every 5 min it will store data.
-MonitorPeriodHours
For how hours data will be keep collecting default value is 1 hour.
-FileName
filename and Location of csv file, by default it keep file on your desktop.

Once you received data you can manipulate it in excel and after filtering and other stuff you can pull cool Chart or graph reports.







 Schedule PowerShell (.PS1 file) script in Windows Task Scheduler - Part3

No comments: