Monday, March 19, 2018

Format Table Columns

Earlier, we saw how to retrieve processes sorted by CPU:

Get-Process | Sort-Object CPU -Descending


Then we winnowed down the list to just the top 10 processes taking CPU cycles:
  
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10


Next we stripped out extraneous detail and just focused on the process name and the CPU using Format-Table:

Get-Process | Sort-Object CPU -Descending | Select-Object `
 -First 10 | Format-Table Name, CPU -Autosize





So it looks like PowerShell calculates out to seven decimal places. Er, millionths of a second? I'm not sure that much precision is necessary. Any way to clean that up?

Sure, using a calculated field:

Get-Process | Sort-Object CPU -Descending | Select-Object `
 -First 10 | Format-Table Name,@{Name="CPU(Min)";Expression` ={"{0:F2}" -f($_.CPU/60)}} -Autosize


 


A calculated field starts with the '@' symbol followed by curly brackets { }. 'Name="CPU(Min)" is what the column header will be labeled, as in "Minutes of CPU time". The Expression is the calculation to apply to the data in that column. In this case, we took the CPU cycles in seconds, divided them by sixty to just get the minutes, and only specified two decimal places (the 'F2' portion.)  How does that look?

 


Much nicer.

No comments:

Post a Comment