Thanks to all who attended the Technet webcast on PowerShell extensions. I’ve corrected the slide with the syntax for expressions. It will be included in the final PowerPoint file you can download from Microsoft.
Here are some clearer examples on using expressions:
#another example with Get-Process
Get-Process | select Name,ID,@{Name=”Working Set”;`
Expression={”{0:N2}” -f ($_.Workingset/1mb)}}
#example with Format-Table
Get-Process |Format-Table Name,ID,StartTime,@{Label=”Age(min)”;`
Expression={(Get-Date).Subtract($_.startTime).Minutes}} -auto
The main difference between what you use for Select vs Format is that Select uses ‘Name’ and Format uses ‘Label’.
Attached you will find a zip file with my .ps1xml files for custom type and view extensions. You’ll need to save them locally and use the appropriate Update cmdlet before you can use them.
I’ve divided up the content into separate ps1 files. You should be able to run them as scripts or simply copy and paste the snippets into PowerShell. If you have any follow-up questions or comments, please post them in the PowerShell forum at ScriptingAnswers.com. It is free, although you need to register.
The line (Get-Date).Subtract($_.startTime).Minutes should reference TotalMinutes. The minutes value is only meaningful if you look at Days & Hours as well.
You are absolutely correct. I wasn’t paying attention when I put that together. I should have used Total Minutes, and even that should be better formatted. Another approach is like this:
Get-Process |Format-Table Name,ID,StartTime,@{Label=”Age”;`
Expression={(Get-Date).Subtract($_.startTime).ToString()}} -auto
This will display the age Days:Hours:Min:Sec:Ms format.
Here’s the MSDN link to information on the -f operator:
http://msdn2.microsoft.com/en-us/library/dwhawy9k(vs.71).aspx
Jeff
Here’s one final version:
Get-Process | where {$_.name -ne "System" -and $_.name -ne "Idle"} | `
sort StartTime -Desc | Format-Table Name,ID,StartTime,@{Label=”Age”;`
Expression={$t=(Get-Date).Subtract($_.startTime);
(($t.days).toString()).PadLeft(2,"0")+":" `
+(($t.hours).toString()).PadLeft(2,"0") `
+":"+(($t.minutes).toString()).PadLeft(2,"0")+":"`
+(($t.seconds).toString()).PadLeft(2,"0")}
} -auto
I’ve filtered out System and Idle processes, sorted by start time in descending order and formatted the age to use leading zeros. I omitted the millisecond value because I didn’t feel it was necessary.
Of course I’m always open to other approaches, especially anything simpler.