Use Foreach-Object instead of Select-Object -expandProperty

by Apr 22, 2011

As you may know, Select-Object can return the content of an object property when you use the parameter -expandProperty. This will get you a list of all software manufacturers of all running processes:

Get-Process | Select-Object -expandProperty Company


Unfortunately, Select-Object -expandProperty has a number of limitations. For example, if there is no company information in a process object, you will get an error and the list is incomplete. As a non-Administrator, you will experience this regularly because you cannot access processes that are owned by someone else.
Instead, a much better and more robust way is to use Foreach-Object:

Get-Process | Foreach-Object { $_.Company }


This approach is fault-tolerant and it also avoids some of the other bugs in Select-Object -expandProperty.


Twitter This Tip!
ReTweet this Tip!