Home PSDKit, or how to convert JSON data to PowerShell code
Post
Cancel

PSDKit, or how to convert JSON data to PowerShell code

If you’re working with APIs and PowerShell you’ve no doubt ran into JSON data before. JSON is great because it is an open data interchange format that is both human and machine-readable. You can read it, and so can Powershell.
But there is a caveat.

If you have a need to store JSON data in your script you have to resort to a very clunkly solution using @" "data": "here" "@.
I frankly have no idea what you call this thing @""@ but its horrible. The data is effectively just a string.
In this post we’re going to have a little look at how we can convert the JSON data to a powershell format of objects, hashtables and arrays.

Desktop View Why did the PowerShell module apply for a job at the comedy club? It heard they were looking for someone great at converting laughs to a well-structured format

The hero in this story is the module PSDKit. It contains the cmdlet ConvertTo-Psd which can take a powershell object and convert it to code.

First we are going to install the module. You can do so using the Install-Module cmdlet.

1
Install-Module -Name PSDKit -Scope AllUsers -Force

Once its installed you can take a piece of data like for example this JSON data:

1
2
3
4
5
6
7
{
    "employee":{
        "name":"John", 
        "age":30, 
        "city":"New York"
    }
}

Convert it to a PowerShell object:

1
2
3
4
5
6
7
8
9
$data = @"
{
    "employee":{
        "name":"John", 
        "age":30, 
        "city":"New York"
    }
}
"@ | ConvertTo-Json

And then we can convert it from a PowerShell object in memory, to code:

1
ConvertTo-Psd -InputObject $data | Out-File 'C:\temp\expoTest.psd1'

Which results in the following:

1
2
3
4
5
6
7
@{
    employee = @{
        name = 'John'
        age = 30
        city = 'New York'
    }
}

You may notice that the original JSON data and the PowerShell code look almost the same and you could convert it by hand. And that’s true. But for example by the time you’re converting an entire Intune policy things get a lot more complicated! The object will be hundreds of lines long with nested arrays and hashtables. And now imagine having to convert multiple templates.

I hope this is useful information and that it has brought a bit of attention to a small part of a very useful module (it does a lot more than this!). Have a great day!

This post is licensed under CC BY 4.0 by the author.