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.
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
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.