
close
close
Chance to win $250 in Petri 2023 Audience Survey
One of the problems many PowerShell beginners have is getting their heads around the idea of objects in the pipeline. They see the output of a command and try to finagle something from the text they see on the screen.
This becomes tricky with object properties that contain a nested object or a collection of objects. You might start with a command like this:
$s = get-service bits
You’ll then look at $s.
A service object with nested objects (Image Credit: Jeff Hicks)
Selecting a property of nested objects (Image Credit: Jeff Hicks)
Attempting to expand nested objects (Image Credit: Jeff Hicks)
Using ForEach to expand nested objects (Image Credit: Jeff Hicks)
$s | select -expandproperty RequiredServices
The easy way to expand a property (Image Credit: Jeff Hicks)
get-service | where {$_.status -eq 'running'} | Select name | out-file c:\work\running.txt
In their heads and perhaps based on experience with command-line tools, they are expecting a text file of only service names. But what they have really done is direct the output of a single property object to text file something that looks like this:
Name ---- Appinfo AudioEndpointBuilder Audiosrv BcmBtRSupport BFE BITS Bluetooth Device Monitor
The proper way is to expand the property so that all you get is the value.
Expanding a single property (Image Credit: Jeff Hicks)
$running = get-service | where {$_.status -eq 'running'}
Let’s assume that all you need is the service name. In earlier versions of PowerShell, we used commands like this:
Using Foreach to list single property values (Image Credit: Jeff Hicks)
$running | select -ExpandProperty Name
But you can also simply treat the variable as a single object and specify a property name.
Expanding a variable (Image Credit: Jeff Hicks)
Expanding a property from an expression (Image Credit: Jeff Hicks)
Another example of expanding a single property from a command (Image Credit: Jeff Hicks)
Expanding nested service properties (Image Credit: Jeff Hicks)
Displaying a single property value from a collection of nested objects (Image Credit: Jeff Hicks)
More in PowerShell
Most popular on petri