Powershell API example

JBrennan
Giga Contributor

Hi All,

It appears that the Powershell example inside the REST API Explorer tab is malformed, specifically:

# Specify request body

{request.body ? "$body = \"" :""}}{}"

This line is not valid Powershell syntax. Can anybody help me out as to what this should be?

find_real_file.png

10 REPLIES 10

JBrennan
Giga Contributor

It looks like another user has asked the same question the day after I posted this - See Powershell ServiceNow API


I see that you Anthony have also seen it and have replied.



Doesn't seem to be much point keeping two threads covering the same issue, I'm happy to close this one.



For the record, if you comment the above mentioned line out #{request.body ? "$body = \"" :""}}{}" the query works but the output is one big block of text instead of nice Powershell objects


Replace the body like this :



$body = @{     #Create body of the POST request


yourfield= ""


yourfield= ""


yourfield= ""


}


$bodyJson = $body | ConvertTo-Json




# Send HTTP request


$response = Invoke-WebRequest -Headers $headers -Method $method -Uri $uri -Body $bodyJson -ContentType "application/json"


Hi Hao,


Thank you very much for your post above!!


JBrennan
Giga Contributor

I've just had a few minutes to put together some screen shots to further troubleshoot and think I have fixed the problem (or at least been able to do want I need).



First things first, lets acknowledge the Service-Now developers have screwed up this line of PowerShell {request.body ? "$body = \"" :""}} and hope they go back and fix it at some stage. I'm no PowerShell expert but assume they are trying to use regex to format the body. The poor mans fix for this is as you mention above to add the $body = @ { name="blar" } (also as seen in this post PowerShell Explore REST Api) but it looks like you have to specify each field you want to return (which the regex would eliminate).



HOWEVER, I have been testing with the Invoke-RestMethod command instead of the Invoke-WebRequest and am able to return each field as a PowerShell object i.e. $response.<fieldname> instead of one big blob of text.



Hope it helps someone else


find_real_file.png



find_real_file.png


Hi Jeremy,


Thank you very much for your posts above - very informative!