How can I configure PowerShell to select an object property (top level or nested) based on the contents of a variable?
I have PowerShell script that reads the contents of a file (JSON), converts it to an object and then selects one of the properties. However, the content is not consistent and the location of the desired property within the JSON may change.
I'd like to be able to set a -PropertyPath
parameter on the script that will enable users to pass in the path to the desired property within the object.
Take the following example, which allows for the selection of an object property based on the value of -PropertyPath
. It works because the property is not nested.
$PropertyPath= "myProperty"
$definition = (Get-Content -Path $definitionFilePath -Raw | ConvertFrom-Json).$PropertyPath
Now take the following failed example where the property to get is nested (and does exist), which fails with no error, but $definition
is empty - presumably because a property called "random.myProperty" does not exist.
$PropertyPath= "random.myProperty"
$definition = (Get-Content -Path $definitionFilePath -Raw | ConvertFrom-Json).$PropertyPath
Any help would be appreciated.