How Do You Print One Attribute (or Element) From The Results of a Built-in PowerShell Command?

Problem Scenario
You are writing a PowerShell script.  You want to extract one value from the results of a command.  You get a set of values all on one line.  It is difficult to parse just what you need. The output values for each attribute are separated by spaces.  Sometimes the output values are blank.  You want to reliably extract one property value from the command. You know that piping the output to an "sls" command will retrieve an entire row.  You could write the output to a file then parse the plain text file.  But you know that writing to the disk unnecessarily can cause disk contention.  You also need to delete the files unless they accumulate.  It is more elegant to leverage the PowerShell objects in memory and avoid writing to disk if possible.  How do you select one property and not the entire row?

Solution
Pipe the output to a "select -expandproperty nameOfProperty" command.  It will look something like this:

complex_command_here | select -ExpandProperty desiredProperty

Here is an example:  Get-PSDrive -Name C | select -ExpandProperty Provider

Replace "Provider" with the attribute you want.  Replace "Get-PSDrive -Name C" with the command that will return the results you want. If you use a variable assignment, you can then use conditional logic based on this sole variable.  This attribute can be the basis of more complex scripts.

Leave a comment

Your email address will not be published. Required fields are marked *