Reputation: 31
I have working powershell code that gets data from a database, I then loop through the rows, convert the row to Json using ConvertTo-Json
and then call Invoke-WebRequest
using the Json body that was created.
I was curious if I could simplify this task?
I know I can do something like this to create JSON out of each row:
($UserToUpdate.Tables[0].Rows | select $UserToUpdate.Tables[0].Columns.ColumnName ) | ConvertTo-Json
I Was thinking I might be able to do something like
($UserToUpdate.Tables[0].Rows | select $UserToUpdate.Tables[0].Columns.ColumnName ) | ConvertTo-Json | Invoke-WebRequest -Headers $headers -Method $method -Uri $uri -Body $body
However I am not sure how to use the results of the previous ConvertTo-Json
as the $body
in the Invoke-Webrequest
.
I may be barking up the wrong tree, but thought it was worth trying!
Upvotes: 0
Views: 560
Reputation: 3326
The Powershell pipeline passes a full copy of your JSON Object through to Invoke-WebRequest
, but Invoke-WebRequest
doesn't know how to deal with it by default.
the easiest thing to do is pipe it into a Foreach-Object
, (aliases of ForEach
or just %
, any work) and then operate on it from there.
... | ConvertTo-Json | Foreach { Invoke-WebRequest -Body $_ -Uri $Uri }
the piped object (in this case your JSON string) will be represented by the $_
variable within the {}
scriptblock after the Foreach
hopefully that helps you get this working.
Upvotes: 1