Skip to content

yer.ac | Adventures of a developer, and other things.

  • About
  • Dev.to

yer.ac | Adventures of a developer, and other things.

Blog to keep track of things I am upto

Consuming a JSON file for automatic params in PowerShell

June 29, 2021 by yer.ac

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.

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Tumblr (Opens in new window) Tumblr
  • Click to share on Pinterest (Opens in new window) Pinterest

Related

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Tumblr (Opens in new window) Tumblr
  • Click to share on Pinterest (Opens in new window) Pinterest

Post navigation

Previous Post:

Using PodGrab & Docker to backup my favorite podcasts (In this case on a QNAP NAS)

Next Post:

Fixing “hostfxr.dll could not be found” within Windows Docker container (.NET installed from dotnet-install.ps1)

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Dev.To Profile

Rich's DEV Profile

Tags

agile Azure AzureDevOps Azure Functions ContinuousImprovement Cosmos DB Cypress DevOps docker dotnet ES6 function-calling GPT Javascript Mocha NLOG Nuget openai podcast podgrab PowerShell python QNAP SCRUM SonarQube Testing TFS VisualStudio VSCODE VSTS wordpress
© 2025 yer.ac | Adventures of a developer, and other things. - Powered by Minimalisticky