The CreatorCon Call for Content is officially open! Get started here.

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

Sorry, One last thing on thing: Again I'm not a PowerShell expert and I'm sure somebody with better skills than I can probably suggest a better way of doing it and/or explain further but I have figured out how to continue to use Invoke-WebRequest but format the output to allow you to reference each field as a PowerShell object (see below ##############)



#Service-Now code sample



# Eg. User name="admin", Password="admin" for this code sample.


$user = "admin"


$pass = "admin"



# Build auth header


$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user, $pass)))



# Set proper headers


$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"


$headers.Add('Authorization',('Basic {0}' -f $base64AuthInfo))


$headers.Add('Accept','application/json')




# Specify endpoint uri


$uri = "https://xxxxxxxxxxxx.service-now.com/api/now/table/cmdb_ci_server?sysparm_limit=1"



# Specify HTTP method


$method = "get"



#SERVICE_NOW TO FIX THE BELOW LINE


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



# Send HTTP request


$response = Invoke-WebRequest -Headers $headers -Method $method -Uri $uri



# Print response


$response.RawContent



####################JB's Edit#####################################
# Convert response from json
$response2 = $response.Content | ConvertFrom-Json



# Now you can select specific fields as PowerShell Objects. Example:
$response2.result | Select name, os, classification



#Example of adding specific field to a string
$response2.result | % {Write-host "The name of the server is: $($_.name)"}



#Example of If statement
$response2.result | % {IF ($_.name -like "*Sacramento*") {Write-host $_.name}}