Search code examples
powershellpowershell-4.0powershell-cmdletpowercli

How to filter out a particular value from PS output


I am running a PS command get-Keyproperty which is returning result in table format at below"

Key                  Label                          Policy     Running  Required
---                  -----                          ------     -------  --------
abc                 UI                               on         True     False  
efg                 UI                               off        True     False 

I want to retrieve value of Policy which is on

How to retrieve Policy value of abc Key?

I am running get-Keyproperty | Select-Object abc but it is not working.


Solution

  • To get the value of Policy try to run

    Get-Keyproperty | Select-Object -ExpandProperty Policy
    

    Even though the command above is the recommended way, you can also get the same result with (Get-Keyproperty).Policy.

    If you want to check if the value matches "on" just do (Get-Keyproperty | Select-Object -ExpandProperty Policy) -eq "on"

    If you want the Policy Value of a certain entry you can either:

    1. Choose the entry over its position in the table

      (Get-Keyproperty | Select-Object -ExpandProperty Policy)[0]

    2. Or by finding it over its value of Key

      Get-Keyproperty | Where-Object {$_.Key -eq "abc" } | Select-Object -ExpandProperty Policy

      As mentioned in the comments, a shorter way of the same command is

      (Get-Keyproperty | ? Key -eq "abc").Policy

      ? is an alias (Get-Alias ?) and the {script block} is only neccessary for more complex expressions which then requires the $_.Key or $PSItem.Key(introduced in PSv3) notation; which both are synonym for the current object in the pipeline . See Get-Help Where-Object.