
close
close
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)
advertisment
$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)
advertisment
$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 from Jeff Hicks
advertisment
Petri Newsletters
Whether it’s Security or Cloud Computing, we have the know-how for you. Sign up for our newsletters here.
advertisment
More in PowerShell
Microsoft’s New PowerShell Crescendo Tool Facilitates Native Command-Line Wraps
Mar 21, 2022 | Rabia Noureen
Most popular on petri
Log in to save content to your profile.
Article saved!
Access saved content from your profile page. View Saved
Join The Conversation
Create a free account today to participate in forum conversations, comment on posts and more.
Copyright ©2019 BWW Media Group