0

The following is a snippet from my PowerShell script where the values for the parameters $book and $author are not getting substituted. Please suggest some techniques that I can apply to fix it or share some code that can help me out.

$body = @{
version = '1.0'
inactive = 'false'
yml = { "Service1:\n book: $book\n author: $author\n "} | ConvertFrom-Json
} | ConvertTo-Json

$request = Invoke-WebRequest -UseBasicParsing -Method Post -Uri $uri -Body 
$body -Headers $headers -ContentType $contentType

$response = ConvertFrom-Json -InputObject $request.Content

1 Answer 1

1

You have some weird stuff going on in this line

... yml = { "Service1:\n book: $book\n author: $author\n "} | ConvertFrom-Json } | ConvertTo-Json

Because it says "do a script block with this body, and try to convert the script block to JSON".

So, if you want to have a JSON string in yml field, you have two options.

  1. Write the proper JSON string yourself:

    @{...put the rest of your elements here...; yml = "{Service1:'', book:'$book', author: '$author'}"
    
  2. Populate a hashtable first and then convert it to JSON string:

    @{...put the rest of your elements here...; yml = @{Service1=''; book='$book'; author='$author'} } | ConvertTo-Json
    
Sign up to request clarification or add additional context in comments.

4 Comments

@vorou...I think you may not have looked at the curly braces carefully.... the ConvertTo-Json is for the outer-most construct and the ConvertFrom-Json is only for that element in that hashtable... Please have another look... thank you for suggesting those 2 options... let me try and I'll let you knkow...
Please ignore my question as I am no longer seeking solutions... It has been taken care of thru some other technology. Really appreciate the hep though.
Please ignore my question as I am no longer seeking solutions... It has been taken care of thru some other technology. Really appreciate the hep though.
@dn_learner glad to hear you made it. Still, if my answer answered the original question, please mark it as an answer.

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.