Public/ConvertTo-JsonL.ps1
Functions/ConvertTo-FlatObject.ps1
You can use the ConvertTo-Json cmdlet in PowerShell to convert an object to a JSON-formatted string.
When using the ConvertTo-Json cmdlet on an array with a single item, using a pipeline will produce a single string:
Suppose that we create an array named $my_array that contains the name of one basketball team.
Suppose that we attempt to pass this array in a pipeline to the ConvertTo-Json cmdlet to convert the item in this array to a JSON-formatted string:

Notice that this returns a single string.

Notice that this returns a JSON-formatted string, just as we intended.
Note #1: If your array has more than one item then you can actually use the pipeline format with the ConvertTo-Json cmdlet without any issues.
Note #2: You can find the complete documentation for the ConvertTo-Json cmdlet in PowerShell here.
PowerShell: How to Sort a Table with Format-Table
PowerShell: How to Sort by Specific Column
PowerShell: How to Use Sort-Object with Multiple Properties
I’m new to powershell so please be patient with me.
I am working to create a script that can generate password in PowerShell for PFX certificate export. First i called the new function to generate the password as shown below
function Generate-RandomPassword{ param ( [Parameter(Mandatory)] [int] $length ) #$charSet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789{}+[]*=:()$^%;_!&#?>.'.ToCharArray() $charSet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.ToCharArray() $rng = New-Object System.Security.Cryptography.RNGCryptoServiceProvider $bytes = New-Object byte[]($length) $key = New-Object Byte[] 16 $rng.GetBytes($bytes) $result = New-Object char[]($length) for ($i = 0 ; $i -lt $length ; $i++) { $result[$i] = $charSet[$bytes[$i]%$charSet.Length] } return (-join $result)
}Secondly, i intend to use the $CertfilePath variable to store the common name of the certificate i intend to export. This specifies the CERT: logical drive, the computer account, and then the Personal identity store and then the -dnsname parameter here dictates which CN i am targeting using the below
$CertFilePath = Get-ChildItem -Path Cert:LocalMachine\MY -dnsname *TARGET*Finally, i want to be able to ConvertTo-SecureString which accepts pipe input, however the the -key parameter is required and is the sticking point here, it is the # of bytes used to convert the plaintext: 128, 192, or 256 bits are valid options. Note that the Generate-RandomPassword integer was lowered to 16, 16*8=exactly 128 bits. I tried to shorten it for compatibility to fit the byte array length of 128 but something about how i am populating this -key value is incorrect with the below
$PfxExportPassword = get-content -path C:\PFX\certs\PASSWORD.txt | ConvertTo-SecureString -key 32When i run the above, i get the below error
ConvertTo-SecureString : The specified key is not valid. Valid key length settings are either 128 bits, 192 bits, or 256 bits.
At line:1 char:80
In this PowerShell tutorial, I will explain how to write JSON to a file in PowerShell.
To write JSON to a file in PowerShell, you can use the ConvertTo-Json cmdlet to convert a PowerShell object into a JSON string, and then output this string to a file using Out-File or Set-Content. For example:
$object | ConvertTo-Json | Set-Content -Path 'file.json'This approach is simple and effective for most scenarios where you need to save JSON data from PowerShell to a file.
Method 1: ConvertTo-Json and Out-File
To write JSON to a file in PowerShell, you can use the ConvertTo-Json cmdlet, which converts a PowerShell object into a JSON-formatted string. Once converted, you can then output the string to a file using the Out-File cmdlet.
Here’s a simple example:
# Create a PowerShell object
$person = @{ FirstName = 'James' LastName = 'Karley' Age = 30
}
# Convert the object to a JSON string
$json = $person | ConvertTo-Json
# Write the JSON string to a file
$json | Out-File -FilePath 'C:\MyFolder\person.json'This script creates a hashtable representing a person, converts it to JSON, and writes it to a file named person.json.
You can see the output in the screenshot below after I executed the script using VS code.

Method 2: ConvertTo-Json and Set-Content
An alternative to Out-File is the Set-Content cmdlet in PowerShell. It’s particularly useful when you need to ensure the file encoding is set correctly, such as UTF-8, which is often required for JSON data.
# Convert the object to a JSON string
$json = $person | ConvertTo-Json
# Write the JSON string to a file with UTF8 encoding
$json | Set-Content -Path 'person.json' -Encoding UTF8This approach is similar to the previous one but specifies the encoding to prevent any issues with character representation in the JSON file.
Method 3: Using Add-Content for Appending Data
If you need to append JSON data to an existing file in PowerShell, you can use the Add-Content cmdlet. This is particularly useful when logging or adding to a JSON array in a file.
# Additional person object
$additionalPerson = @{ FirstName = 'Jane' LastName = 'Smith' Age = 25
}
# Convert the additional person to JSON
$additionalJson = $additionalPerson | ConvertTo-Json
# Append the JSON string to the existing file
$additionalJson | Add-Content -Path 'C:\MyFolder\person.json'This script will add the additionalJson content to the people.json file without overwriting the existing data.
You can see the output in the screenshot below after I executed the PowerShell script using VS code.

Method 4: Export-Clixml for Complex Objects
# Export the object to an XML file
$person | Export-Clixml -Path 'person.clixml'While not strictly JSON, this method is included for completeness as it can handle complex serialized data that JSON might not.
Method 5: Using JSON.net Library
For full control over the JSON serialization process, you can use the Newtonsoft JSON.net library. This library offers more features than the built-in PowerShell cmdlets.
First, you need to install the library:
# Install the Newtonsoft.Json library
Install-Package -Name Newtonsoft.JsonThen, you can use it to serialize and write the JSON data:
# Load the Newtonsoft.Json assembly
Add-Type -Path 'C:\path\to\Newtonsoft.Json.dll'
# Serialize the object to JSON using JsonConvert
$json = [Newtonsoft.Json.JsonConvert]::SerializeObject($person)
# Write the JSON string to a file
Set-Content -Path 'person.json' -Value $json -Encoding UTF8This method is particularly useful when dealing with complex JSON structures or when you need to customize the serialization process beyond what the ConvertTo-Json cmdlet offers.
Conclusion
PowerShell offers several ways to write JSON data to a file. By utilizing the ConvertTo-Json cmdlet with Out-File or Set-Content, you can easily serialize and save JSON data. For appending data, Add-Content is your go-to cmdlet. And for the most complex scenarios, leveraging the JSON.net library gives you the flexibility and power to manage JSON serialization in PowerShell with precision.
In this PowerShell tutorial, I have explained how to write JSON to a file in PowerShell using different methods.
You may also like:



