0

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!

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.