Search code examples
powershellpowershell-5.0

Get nested values in one line


I'm new to powershell so I had a simple question. Suppose I have the following powershell code:

$t = Get-SomeData -someParam someParamValue
$t.SomeProperty.SomeNestedField

The second command above will print the value of SomeNestedField, which is nested inside t's property called someProperty

Can I combine these two lines into one powershell command (perhaps through piping), so that the output of the second command comes from just one command overall ?

Requirement is that it should print the value, not assign it to some powershell variable ..

Perhaps something like:

Get-SomeData -someParam someParamValue | SomeProperty | SomeNestedField

Some info that might help out:

Suppose I change above code to this:

$t = Get-SomeData -someParam someParamValue
$u = $t.SomeProperty
$t.GetType()
$u.GetType()

When I execute $t.GetType(), the BaseType listed is a class, but if I do $u.GetType(), it's BaseType is listed as System.ValueType


Solution

  • You can use SELECT aka SELECT-OBJECT

    Get-SomeData -someParam someParamValue | select -ExpandProperty SomeProperty
    

    Or ()

    (Get-SomeData -someParam someParamValue).SomeProperty.SomeNestedField