KFL KFL - 7 months ago 24
PowerShell Question

How to get an object's property's value by property name in PowerShell?

In PowerShell, how do you get an object's property value by specifying its name (a string)? I want something like the following:

$obj = get-something

# View the object's members:
$obj | gm

# I could retrieve a property by doing so:
write-host $obj.SomeProp

# But for many purposes, I would really want to:
write-host $obj | Get-PropertyByName "SomeProp"


Is there something similar to "Get-PropertyByName" in PowerShell?

Answer

Sure

write-host ($obj | Select -ExpandProperty "SomeProp")

Or for that matter:

$obj."SomeProp"