Adding a specific property to each json object in an array in powershell

Question:

I have an array of JSON objects and I want to add a particular property to each object present.

For example, the array is as follows:

I want to add “source”: “CPU” to all objects. How do I go about doing that? I am new to PowerShell and haven’t been able to get this done.

Answer:

You could do the following:

This assumes your JSON input is in a variable named $JSON, you’ll need to replace this with however you access your JSON content (e.g Get-Content yourfile.json).

Once you have the JSON, we use ConvertFrom-JSON to convert it to a PowerShell object.

We then use the pipeline to send this to a ForEach-Object loop which uses the Add-Member cmdlet to add a property to each item in the collection (the current item is represented by $_) named ‘Source’ with a value of ‘CPU’. Per the comments from mklement0, it is necessary to use the -PassThru switch to send the result back to the pipeline.

Then we pipe that output to ConvertTo-JSON to convert it back.

Source:

Adding a specific property to each json object in an array in powershell by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply