
close
close
I think by nature most people are picky. In PowerShell, this is actually a positive attribute. PowerShell is designed to give you a lot of information. Sometimes more than you really need. PowerShell is also designed to display command results that someone from Microsoft, or a vendor in the world of third-party cmdlets, thought you would most likely want to see or use. Of course, you know that there is always much more to the picture than what you see. Once you discover what you can use, you can afford to be a bit pickier and the cmdlet that makes this easy is Select-Object. If you are new to using PowerShell objects, read Introduction to Objects in PowerShell on Petri IT Knowledgebase.
There are a few ways to use Select-Object. Perhaps the most important way is to use it to display a subset of object properties. You should know that properties you see when you run a command like Get-Process are not the only properties. In some cases, what you see isn’t even the actual property name. The best way is to use Get-Member to discover the actual property names.
get-process | Select ID,Name,@{Name="WS(KB)"; Expression = { $_.WS/1kb}},Path
The hashtable will define a property called WS(KB), which will have a value of the current WS value divided by 1KB.
dir c:\work -file | Select Name,@{Name="Size";Expression={$_.length}}, CreationTime,LastWriteTime,@{Name="ModifiedAge";Expression={(Get-Date) - $_.lastwritetime}} | sort ModifiedAge -Descending | Out-Gridview -Title "Work Files"
I created a few custom properties here. The first is essentially an alias property for file length that I’m calling Size, which I find more meaningful. I also created a new property called ModifiedAge that calculates a timespan indicating how long it has been since the file was modified. When you create these types of custom properties with Select-Object, they are passed on in the pipeline, which means you use can use them with other commands such as Sort-Object. That is exactly what I am doing here. I’m sorting on the new ModifiedAge property and piping the results to Out-Gridview.
CreationTime,LastWriteTime,@{Name="ModifiedAge";Expression={(Get-Date) - $_.lastwritetime}} | sort ModifiedAge -Descending | Select -first 10 | format-table
There’s nothing wrong with using Select-Object twice. In this case, I have to because I need to define my custom property and then sort on it before I can select the first 10 objects.
advertisment
More in PowerShell
Microsoft’s New PowerShell Crescendo Tool Facilitates Native Command-Line Wraps
Mar 21, 2022 | Rabia Noureen
Most popular on petri