whizkid
whizkid

Reputation: 113

Is there a way to write this Powershell script in a single line,or perhaps in a simpler way?

I am using this PowerShell script below to find the memory usage of a Windows Server. I would like to know if there is a simpler/cleaner way so I can quickly copy-paste to the problem server.

$ComputerMemory = Get-WmiObject -ComputerName $Server -Class win32_operatingsystem -ErrorAction Stop
$Memory = ((($ComputerMemory.TotalVisibleMemorySize - $ComputerMemory.FreePhysicalMemory)*100)/ $ComputerMemory.TotalVisibleMemorySize)
$RoundMemory = [math]::Round($Memory, 2)
$RoundMemory

Upvotes: 1

Views: 163

Answers (2)

Theo
Theo

Reputation: 61253

Another approach using the newer Get-CimInstance cmdlet:

'{0:N2}' -f (Get-CimInstance -ComputerName $Server -ClassName Win32_OperatingSystem | 
             Select-Object @{Name = 'Memory'; Expression = {
                 (($_.TotalVisibleMemorySize - $_.FreePhysicalMemory)*100)/ $_.TotalVisibleMemorySize}
             }).Memory

Upvotes: 2

Avshalom
Avshalom

Reputation: 8899

A little bit shorter:

Gwmi win32_operatingsystem | % {
(($_.TotalVisibleMemorySize - $_.FreePhysicalMemory) * 100 / 
$_.TotalVisibleMemorySize).ToString(".00")
}

Upvotes: 3

Related Questions