Get Service Memory Usage In PowerShell

Services are used to complete to provide services for different tasks. Like regular or user processes the services also process those that use CPU and memory. As the services generally run longer than a process they use memory and may require more memory which is not released over time even if there is no need for memory. Detecting this type of issue is important to free memory for other processes. PowerShell can be used to get service memory usage in different ways. The wmi and cim commands can be used to get service memory usage via the PowerShell command line interface.

Get Service Memory Usage Using WMI

The wmi command is the popular command used to get and configure windows operating system internals. The Get-WMIIbject is provided by PowerShell natively to use WMI features. We can use the Get-WMIObject command in order to display specified service memory usage. In the following example, we get the “WinDefend” service memory usage.

PS> $ServiceName = "WinDefend"
PS> $Service=Get-WmiObject Win32_Service -Filter "name = '$ServiceName'"
PS> $ProcessID = $Service.ProcessID
PS> $ProcessMem = Get-WmiObject Win32_Process -Filter "ProcessId = '$ProcessID'"
PS> $MemSizeInMB = $ProcessMem.WS/1MB

We can the service memory size in MB like below.

PS> $MemSizeInMB

Get Service Memory Usage using CIM

The cim command named Get-CIMInstance also provides the very same method with the Get-WmiObject.

PS> $ServiceName = "WinDefend"
PS> $Service=Get-CIMInstance Win32_Service -Filter "name = '$ServiceName'"
PS> $ProcessID = $Service.ProcessID
PS> $ProcessMem = Get-CIMInstance Win32_Process -Filter "ProcessId = '$ProcessID'"
PS> $MemSizeInMB = $ProcessMem.WS/1MB

We can the service memory size in MB like below.

PS> $MemSizeInMB

Get Service Memory Usage For Remote System/Windows

We can get a remote system or windows service memory usage by using the previously defined Get-WmiObject or Get-CIMInstance commands. We will also use the -ComputerName attribute of the Get-WmiObject command. In the following example, we get the WinDefend service memory usage of the remote computer with IP address 102.168.1.10

PS>  $ServiceName = "WinDefend"
PS> $Service=Get-WmiObject Win32_Service -ComputerName 192.168.1.10 -Filter "name = '$ServiceName'"
PS> $ProcessID = $Service.ProcessID
PS> $ProcessMem = Get-WmiObject Win32_Process -ComputerName 192.168.1.10 -Filter "ProcessId = '$ProcessID'"
PS> $MemSizeInMB = $ProcessMem.WS/1MB

We can print the remote system service memory usage with the following command.

PS> $MemSizeInMB

List Services According To Memory Usage

We can list services according to their memory usage. The Get-WmiObject command is used with the Sort-Object command below. In the following example, we sort the top 20 memory using windows services.

PS> Get-WmiObject Win32_Service| Sort-Object -Property ws -Descending | Select-Object -first 20 ProcessID,Name,WS

Leave a Comment