Monday, November 23, 2015

Using Powershell to work with Json

Today I decided to look into working with Json in Powershell.  Json is rapidly overtaking Xml as the preferred format for describing projects and build artifacts, so it makes sense to learn how to integrate it with tools such as AppVeyor scripts, Visual Studio Team Services Build Tasks or Octopus deployment steps.

A quick search online led me to discover the following two Poweshell cmdlets that can be used when working with Json:

• ConvertFrom-Json
• ConvertTo-Json

Using cmder, I created a new Powershell tab and started typing:

> cd \temp
> md jsontests
> new-item "testjson.js"
> notepad "testjson.js"

I then added the following content to the file:

    Name: "Darren Neimke",
    Age: "42",
    Gender: "Male" 

Flicking back to the console, I typed the following Powershell command to confirm that I could read the content:

Get-Content "testjson.js"

Piping the raw content to ConvertFrom-Json produced the following:

To expand my use of Powershell, I opened the Powershell ISE and created the following script:

$path = ".\testjson.js"
$raw = Get-Content $path -raw

$obj = ConvertFrom-Json $raw
$obj.Age = 45     # I always lie about my age!

Write-Host $obj   # Dump obj to console

Set-Content $path $obj

The ISE amazed me in how it was able to infer the schema of the $obj instance and provided me with Intellisense after that!

Running that script updated the value of the Age property and saved it back to the file.

Things I Learned:

  • Using ISE to create a Powershell script
  • How to pass the content of a file to another cmdlet using piping and variables
  • Updating Json content using variables
  • Saving a file


No comments:

Post a Comment