Add variables in JSON file into powershell


I am trying to add variable in JSON file for using that file into Invoke-RestMethod command. But while running this here string ($body) I am not able to extract values out of these variables $Name and $SerialNumber. Below is my code. Please help.

$Body = @"
“hardware”: {
“name”: $Name,
“bio”: {
“manufacturer”: “Lenovo”,
“ssn”: $SerialNumber,
“model”: “T470”,

Thanks in advance

I’m not sure if I understood what you’re trying to do. If you want to create a JSON object it might be easier to create it from a PowerShell object (hash table) instead of a here string.

$Body = @{
    hardware = @{
        name = $Name
        bio  = @{
            manufacturer = 'Lenovo'
            ssn          = $SerialNumber
            model        = 'T470'

$Body | ConvertTo-Json

And BTW: Please format your code as code. Thanks. :wink:

Actually the code I posted was a payload in JSON format that I will use into

Invoke-RestMethod -Method PUT -Headers $header -Uri $URI2 -Body $Body

Let me see If your solution works for me

Did you create it by hand? If the answer is “yes” - why? :wink:

Please format your code as code. Thanks.

Actually I download full payload from online then there were many attributes that I do not need, so I delete them.

Basically my question is, Is it possible to store variable in a payload (JSON) in powershell so that I can enumerate values in that variable by using foreach from CSV?

I am - again - not sure if I understand. You can do whatever you need to do. But if I got you right I think it would be easier to work with proper objects because PowerShell is made for. And when you need this objects to be converted to JSON you can do whenever you need.

CSV files or CSV data are best for structured data. The data you seem to be dealing with here are obviously hierarchical data. You could save them for later use with Export-CliXML or as strings in JSON or XML. But it will be easier to convert them before manipulating them.

1 Like

Thank You so much @Olaf

It worked for me, so I have used hash table as you suggested, convert to JSON and used final output in Invoke-Restmethod.

Great. :+1:t4: I’m glad it helped. :slightly_smiling_face: