Consuming a JSON file for automatic params in PowerShell
More of a note for future me…. Typically in PowerShell when there is a requirement for reading an external file to set parameters, I would read in a file using the Get-Content
and converting it to JSON, perhaps something like
$json = Get-Content 'C:\file.json' | Out-String | ConvertFrom-Json
# To an object:
$myobject= New-Object MyObject ($json.ItemA, $json.ItemB, $json.ItemC)
# Individual mappings
$ItemA = $json.ItemA
$ItemB = $json.ItemA
...
The problem with this is that if you have a particularly large or complex JSON file it could be problematic to map every field. Instead we can make use of the New-Variable
command in a loop.
$myJson= (Get-Content File.json | ConvertFrom-Json)
$myJson.PSObject.Properties | ForEach-Object {
New-Variable -Name $_.Name -Value $_.Value -Force
}
Which now means a file like:
{
"PropertyA": "Hello, World"
}
Could be called like $PropertyA
within the script.
Of course, it may be best to include a prefix when calling New-Variable
so properties have better naming conventions- for example $param_PropertyA.