PowerShell

How to Use PowerShell 7 to Work with JSON Files

Though there are many file formats used for configuration and data storage. JSON, or JavaScript Object Notation, files have become very common. They offer an easy to understand and compact format to define information. In addition, they integrate exceptionally well within PowerShell. Functionality such as the ability to be imported as pipelinable objects that can be subsequently exported.

What’s changed in PowerShell 7 to enhance support for JSON? There are no new cmdlets, but there have been some functionality changes to the existing cmdlets.

JSON Support in PowerShell

Before diving into the new functionality, how does PowerShell work with JSON? Let’s walk through a few examples. We will explore how to import JSON, manipulate an object, and export the JSON to a file that can be later consumed.

Import JSON into PowerShell

First, we want to consume a JSON file and then update the values for later use. This type of technique is often used when storing information about a given system, for example, the computer name, environmental properties, etc. In this example, we are going to use a simple JSON file.

Sponsored Content

Maximize Value from Microsoft Defender

In this ebook, you’ll learn why Red Canary’s platform and expertise bring you the highest possible value from your Microsoft Defender for Endpoint investment, deployment, or migration.

computer.json

{
  "SystemName": "TestSystem",
  "LastBoot": "3/28/2020 11:27:15 AM",
  "User": "TestUser",
  "LoggedOn": true
}

By retrieving the content of the JSON file and then converting that content from JSON, a standard PowerShell object is output.

Get-Content -Path "D:\computer.json" | ConvertFrom-JSON

How is the object actually seen by PowerShell? When the JSON is imported, PowerShell converts the data into a PSCustomObject and attempts to match the properties into their types, such as string or bool types.

Exporting JSON Data from PowerShell

Similar to importing JSON, we are able to export a PowerShell object that has been modified or changed. Adding to our above example, what if we want to add a property to our existing imported JSON, such as the PowerShell version. After we save our imported content to a variable, we can then add on a new property.

$JSON = Get-Content -Path "D:\computer.json" | ConvertFrom-JSON
$JSON | Add-Member -Name "PSVersion" -MemberType NoteProperty -Value "7.0"

Now that we have added the new property to our object, let’s export this object and overwrite our existing JSON file.

$JSON | ConvertTo-JSON | Out-File "D:\computer.json"

As you can tell, the new property PSVersion has been added and can be appropriately updated as necessary.

Testing our JSON

In any script or function, it is crucial to test the input and output to make sure that the data is not corrupted or that it will cause further issues down the line. Thankfully, PowerShell added Test-JSON in version 6.x. We have two options, pass in a file as a string that Test-JSON can operate on, or a pass a string from the command-line itself.

Get-Content -Path "D:\computer.json" -Raw | Test-JSON

Note that Get-Content is using the Raw parameter. This returns the file content as one single string instead of an array of strings which Test-JSON cannot process.

What if we want to send in just a simple JSON string to make sure that it’s valid before we save the data? Thankfully, this is also very simple to do with Test-JSON.

'{
  "SystemName": "TestSystem",
  "LastBoot": "3/28/2020 11:27:15 AM",
  "User": "TestUser",
  "LoggedOn": true,
  "PSVersion": "7.0"
}' | Test-JSON

New Features in PowerShell 7

Now that you know how to work with JSON in PowerShell, what does version 7 bring to the table to help enhance support for JSON data? There are a few new parameters available for ConvertTo-JSON and ConvertFrom-JSON that will help with edge cases and the transformation of JSON data.

ConvertTo-JSON

There are two new parameters available as seen below.

  • EnumsAsStrings
  • AsArray

EnumsAsStrings

Although not typically used as much in PowerShell, an enum is a structured data type that enables a variable to be a set of predefined constants. When referencing an enum, the resulting value is a zero-based index. When outputting an enum value from PowerShell to JSON, the numerical value itself would be output, which isn’t always ideal. Often, the string name of the enum would be preferable.

Without the EnumsAsStrings parameter defined, we can see just the values being output.

With the EnumsAsStrings parameter, the correct string names are shown.

AsArray

Similar to how the EnumsAsStrings works, AsArray will wrap pipeline input as an array whether or not it is a single item or multiple items.

ConvertFrom-JSON

Just like ConvertTo-JSON, ConvertFrom-JSON has added a new parameter and changed some functionality.

  • NoEnumerate

NoEnumerate

Prior to PowerShell 7 the default behavior of ConvertFrom-JSON was to not unwrap collections by default. This meant that if a JSON array was passed into PowerShell it would be seen as a single object and not as multiple objects.

# PowerShell 5.1
PS> ('["first","second","third"]' | ConvertFrom-JSON | Measure-Object).Count
1

In PowerShell 7, the new behavior is to unwrap collections which is much more in line with how most cmdlets and functions work within PowerShell.

Image # Expand

By using the NoEnumerate property, this will change the default behavior back to the original method used prior to PowerShell 7.

Image # Expand

Changed Depth Behavior

One final note on ConvertFrom-JSON, the Depth parameter now allows much larger values than it did prior to PowerShell 7. Starting in PowerShell 7, the depth now has a default of 1024 but allows up to [Int]::MaxValue which is a vast difference from the 101 limit that older versions of PowerShell had.

Conclusion

Using and manipulating JSON content in PowerShell is easy to do and offers any number of ways to transform the data to meet your exact needs. Many of the additions that have been added in recent years are community requested additions to make working with JSON that much easier. PowerShell 7 has continued that tradition and expanded even further on the usefulness of the built-in PowerShell JSON functionality.

Related Topics:

BECOME A PETRI MEMBER:

Don't have a login but want to join the conversation? Sign up for a Petri Account

Register
Comments (0)

Leave a Reply

Entrepreneur, hustler, husband, dad, Automator, content producer, published author, Microsoft MVP, DevOps pro and passionate problem-solver.
External Sharing and Guest User Access in Microsoft 365 and Teams

This eBook will dive into policy considerations you need to make when creating and managing guest user access to your Teams network, as well as the different layers of guest access and the common challenges that accompany a more complicated Microsoft 365 infrastructure.

You will learn:

  • Who should be allowed to be invited as a guest?
  • What type of guests should be able to access files in SharePoint and OneDrive?
  • How should guests be offboarded?
  • How should you determine who has access to sensitive information in your environment?

Sponsored by:

 
Live Webinar: Active Directory Security: What Needs Immediate Priority!Live on Tuesday, October 12th at 1 PM ET

Attacks on Active Directory are at an all-time high. Companies that are not taking heed are being punished, both monetarily and with loss of production.

In this webinar, you will learn:

  • How to prioritize vulnerability management
  • What attackers are leveraging to breach organizations
  • Where Active Directory security needs immediate attention
  • Overall strategy to secure your environment and keep it secured

Sponsored by: