Powershell v5.1 Invoke-RestMethod Error Parsing Body - powershell

I'm a beginner with Powershell who's trying to send a PUT request to Microsoft Azure to create an Application Insights log query. I'm able to get this working in Postman, but not in a powershell script. This is the error that I'm getting when running the script:
Invoke-RestMethod : {"code":"Unexpected character encountered while parsing value: S. Path '', line 0, position 0.","message":"Unexpected character encountered while parsing value: S. Path '', line 0, position 0.","innererror":{"diagnosticcontext":"f2843c54-dad7-49b5-92ab-e1dadd40e145","time":"2020-07-24T19:59:45.7979293Z"}}
At C:\Users\thophan\source\Update-AiLogQueries.ps1:58 char:9
+ Invoke-RestMethod -Method Put -Uri $uri -Header $header -Body ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
From looking at the Microsoft documentation, it looks like it's supposed to be able to take in a hashtable for the body, and I'm quite certain my syntax looks exactly the same as the one from the exameple, so I'm not sure what's going on. Below is an excerpt from my script:
$scope = "shared"
$header = #{
"Authorization" = "Bearer $token"
}
$uri = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$rgName/providers/microsoft.insights/components/$aiName/analyticsItems/item?api-version=2020-02-02-preview"
$difference = Compare-Object -ReferenceObject $localQueryList.value -DifferenceObject $response
if ($difference -ne $null)
{
$difference.ForEach(
{
$body = #{
Scope = $scope
Type = "query"
Name = $_.InputObject.Name
Content = $_.InputObject.Content
}
Invoke-RestMethod -Method Put -Uri $uri -Header $header -Body $body
})
}
UPDATE: Here is the documentation that I was looking at, as requested.
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-restmethod?view=powershell-5.1

The API requires that the body be a JSON string. You can do a simple conversion (using ConvertTo-Json) in your Invoke-RestMethod command and set the content type accordingly.
Invoke-RestMethod -Method Put -Uri $uri -Header $header -Body ($body | ConvertTo-Json) -ContentType 'application/json'

Related

RestAPI authentication with PowerShell

I am trying to access the API of OpenProvider using PowerShell and I can't seem to get past Authentication.
The documentation for the API is here : https://support.openprovider.eu/hc/en-us/articles/360025683173-Getting-started-with-Openprovider-API
And my code looks like this:
$EndPoint = "https://api.openprovider.eu/v1beta/auth/login"
function Get-ConfHeaders
{
##Configure headers
$Headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$Headers.Add("ip","0.0.0.0")
$Headers.Add("username","myusername")
$Headers.Add("hash","APIpasswordhashgoeshere")
return $Headers
}
$header = Get-ConfHeaders
Invoke-RestMethod -Method Post -Uri $EndPoint -Headers $header
The response get is :
Invoke-RestMethod : The remote server returned an error: (500) Internal Server Error.
At line:36 char:1
+ Invoke-RestMethod -Method Post -Uri $EndPoint -Headers $header
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I am by no means an expert when it comes to API and any help would be appreciated.
Ok, I think the API documentation here leaves a lot to be desired.
You need to include the authentication in the body and it needs to be converted to JSON format. So the working code looks like this:-
$EndPoint = "https://api.openprovider.eu/v1beta/auth/login"
function Get-ConfHeaders
{
##Configure headers
$Headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$Headers.Add("ip","0.0.0.0")
$Headers.Add("username","username")
$Headers.Add("password","passwordhere")
return $Headers
}
$header = Get-ConfHeaders | ConvertTo-Json
Invoke-RestMethod -Method Post -Uri $EndPoint -body $header -ContentType 'application/json'
Thanks for the help everyone.

Azure DevOps Server Invoke-RestMethod Error: No API version provided for the "PUT" request

Based on this PowerShell example from Etienne Tremblay I try to pass data to the Azure DevOps Server (2019.0.1) REST API.
In this example I would like to modify the description text of a project (just for test reasons):
# DEMO 5 Update an environement build variable
Write-Host "Demo 5"
$projects.value | ForEach-Object {
$project = $_.name
$buildManagementAreaId = "efc2f575-36ef-48e9-b672-0c6fb4a48ac5"
$tfsBaseUrl = GetUrl -orgUrl $orgUrl -header $header -AreaId $buildManagementAreaId
# https://learn.microsoft.com/en-us/rest/api/azure/devops/build/definitions/list?view=azure-devops-rest-5.0
$relDefUrl = "$tfsBaseUrl$project/_apis/build/definitions?api-version=5.0"
Write-Host "Requesting URL: $relDefUrl" -ForegroundColor Yellow
$result = Invoke-RestMethod $relDefUrl -Method Get -ContentType "application/json" -Headers $header
$relDefs = $result.value
if($relDefs.count -gt 0){
Write-Host "$project $($relDefs.count) build def founds" -ForegroundColor Blue
$relDefs | ForEach-Object {
$relDef = $_
$relDefExpanded = Invoke-RestMethod "$($relDef.url)?`$Expand=Environments&api-version=5.0" -Method Get -ContentType "application/json" -Headers $header
$relDefExpanded.project.description = "Hallo!!!"
$body = $relDefExpanded | ConvertTo-Json -Depth 100 -Compress
$body = [System.Text.Encoding]::UTF8.GetBytes($body)
#ERROR OCCURS HERE
$updateResult = Invoke-RestMethod "$($relDef.url)?api-version=5.0" -Method Put -ContentType "application/json" -body $body -Headers $header
Write-host "Variable value after: $($updateResult.project.description)" -ForegroundColor Green
}
}
}
Hints:
$projects get defined before in the script (demo1)
the original script change a variable not a description (both versions don't work)
The Error occurs on:
$updateResult = Invoke-RestMethod "$($relDef.url)?api-version=5.0" -Method Put -ContentType "application/json" -body $body -Headers $header
with the message:
Invoke-RestMethod: {"$ id": "1", "innerException": null, "message": "No API version provided for the" PUT "request The version must either be part of the" Accept "header (eg
\ "application / json; api-version = 1.0 \") or as a query parameter (for example, "? api-version = 1.0")
. Will "," type name ":" Microsoft.VisualStudio.Services.WebApi.VssVersionNotSpecifiedException,
Microsoft.VisualStudio.Services.WebApi","typeKey":"VssVersionNotSpecifiedException","errorCode":0,"eventId":3000}
In C:\Users\mkober\Desktop\Azure DevOps Console\WriteAPI.ps1:75 Zeichen:29
+ ... ateResult = Invoke-RestMethod "$($relDef.url)?api-version=5.0" -Metho ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Final URL:
http://138.202.18.216:8070/Samples/19e02b27-74ab-40dd-a519-ece38fafa870/_apis/build/Definitions/11?revision=5?api-version=5.0
You just need to fix the url, change the ? before the api-version to &:
?revision=5&api-version=5.0
The revision and the api-version is parameters, if you have only one parameter you use ? but when you want to use more you need to append them with &.

How to attach CSV file to Service Now incident via REST API using PowerShell?

I need to attach the file either xlsx or CSV to a particular incident via SNOW REST API using PowerShell script. I have tried with the below code:
if (!$script:ServiceNowCreds) {
$script:ServiceNowCreds = Get-Credential
}
$snow_url = 'https://dev652xx.service-now.com/api/now/table/incident'
$Body = #{
'number' = 'INC00xx059'
}
$result = Invoke-RestMethod -Uri $snow_url -Credential $script:ServiceNowCreds -Body $Body -ContentType "application/json"
$result.result | select sys_id, number | ForEach-Object {
$Upload_snow_url ='https://dev652xx.servicenow.com/api/now/attachment/upload'
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add('Content-Type','text/csv')
$headers.Add('Accept','*/*')
$sys_id = $_.sys_id
$incident_number = $_.number
$UploadBody = #{
'table_name'='incident';
'table_sys_id'=$sys_id;
'file_name' = 'C:\Users\suganthanraj.p\Documents\Servers.csv'
}
$uploadParam = $UploadBody | ConvertTo-JSon
Write-Host $sys_id
Write-Host $incident_number
$UploadResult = Invoke-RestMethod -Uri $Upload_snow_url -Credential $script:ServiceNowCreds -Body $uploadParam -Method Post -Headers $headers
$UploadResult
}
When I execute the above script I am getting the below error:
Invoke-RestMethod : The remote server returned an error: (415) Unsupported
Media Type.
At C:\Users\suganthanraj.p\Desktop\SNOW-UploadAttachment.ps1:39 char:21
+ ... oadResult = Invoke-RestMethod -Uri $Upload_snow_url -Credential $scr ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Try changing you content type to "multipart/form-data"
$headers.Add('Content-Type','multipart/form-data')
$UploadBody = #{
'table_name'='incident';
'record_sys_id'=$sys_id;
'uploadFile' = 'C:\Users\suganthanraj.p\Documents\Servers.csv'
}
The error says "The remote server returned an error: (415) Unsupported
Media Type."
Doco on the api can be found here:
https://docs.servicenow.com/bundle/geneva-servicenow-platform/page/integrate/inbound_rest/reference/r_AttachmentAPI-POSTmultipart.html
Your best option would be leverage the OOB Attachment API in ServiceNow. You will need to make a post call from powershell. Powershell has two options for this Invoke-RestMethod and Invoke-WebRequest. I have had better luck with the latter when trying to POST. You might also first build your rest call in Postman make sure you can get the attachment into ServiceNow, then worry about writing your PS.
$Body = #{
User = 'jdoe'
password = 'P#S$w0rd!'
}
$LoginResponse = Invoke-WebRequest 'http://www.contoso.com/login/' - SessionVariable 'Session' -Body $Body -Method 'POST'
$Session
$ProfileResponse = Invoke-WebRequest 'http://www.contoso.com/profile/' -`WebSession $Session $ProfileResponse`
Finally i found answer from the below link
https://community.servicenow.com/community?id=community_question&sys_id=d3707023dbaceb8023f4a345ca961949 and below is the code:
# Eg. User name="admin", Password="admin" for this code sample.
$user = "admin"
$pass = "XXX"
# 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')
$headers.Add('Content-Type','application/json')
# Specify endpoint uri
$uri = "https://dev652XX.service-now.com/api/now/attachment/file?table_name=incident&table_sys_id=850XXXXX2200e0ef563dbb9a71c1&file_name=TreeSizeReport.csv"
# Specifiy file to attach
$fileToAttach = "C:\Users\suganthanraj.p\Desktop\TreeSizeReport.csv"
# Specify HTTP method (POST, PATCH, PUT)
$method = "POST"
# Send HTTP request
$response = Invoke-WebRequest -Headers $headers -Method $method -Uri $uri -InFile $fileToAttach
# Print response
$response.RawContent

Issue when updating build definition using the REST api of VSTS

I want to update a variable in my build definition but when it tries to run the Invoke-RestMethod I receive the following exception:
Invoke-RestMethod : {"$id":"1","innerException":null,"message":"This request expects an object in the request body,
but the supplied data could not be
deserialized.","typeName":"Microsoft.TeamFoundation.Build.WebApi.RequestContentException,
Microsoft.TeamFoundation.Build2.WebApi, Version=14.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a","typeKey":"RequestContentException","errorCode":0,"eventId":3000}
At D:\a\_temp\231f1be5-edc0-4bd9-a2e4-efd23a8308d1.ps1:42 char:1
+ Invoke-RestMethod -Method Put -Uri "$($projectDef.Url)&api-version=2. ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Everything else seems to work, I get the build definition, I can update the variable but when I try to PUT the json back using the Invoke-RestMethod it fails.
Below is the used code which runs in a Powershell inline script:
# This script is intended to be used for PowerShell script tasks in VSTS in "inline mode"
$valueName = 'ProjectBuildNumber'
$token = 'MYTOKENCODE'
$uriRoot = $env:SYSTEM_TEAMFOUNDATIONSERVERURI
$ProjectName = $env:SYSTEM_TEAMPROJECT
$ProjectId = $env:SYSTEM_TEAMPROJECTID
$uri = "$uriRoot$ProjectName/_apis/build/definitions?api-version=2.0"
# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "", $token)))
$header = #{Authorization = ("Basic {0}" -f $base64AuthInfo)}
# Get the list of Build Definitions
$buildDefs = Invoke-RestMethod -Uri $uri -Method Get -ContentType "application/json" -Headers $header
# Find the build definition for this project
$buildDef = $buildDefs.value | Where-Object { $_.Project.id -eq $ProjectId }
if ($buildDef -eq $null)
{
Write-Error "Unable to find a build definition for Project '$ProjectName'. Check the config values and try again." -ErrorAction Stop
}
# NOTE: ensure we call the v 2.0 api! (both get and put calls need the same api versions!)
# get its details
$projectDef = Invoke-RestMethod -Uri "$($buildDef.Url)?api-version=2.0" -Method Get -ContentType "application/json" -Headers $header
if ($projectDef.variables.$valueName -eq $null)
{
Write-Error "Unable to find a variable called '$valueName' in Project $ProjectName. Please check the config and try again." -ErrorAction Stop
}
# get and increment the variable in $valueName
[int]$counter = [convert]::ToInt32($projectDef.variables.$valueName.Value, 10)
$updatedCounter = $counter + 1
Write-Host "Project Build Number for '$ProjectName' is $counter. Will be updating to $updatedCounter"
# Update the value and update VSTS
$projectDef.variables.$valueName.Value = $updatedCounter.ToString()
$projectDefJson = $projectDef | ConvertTo-Json -Depth 50 -Compress
# when we build the URL need to cater for if the Project Definition URL already has parameters or not.
$separator = "?"
if ($projectDef.Url -like '*?*')
{
$separator = "&"
}
$putUrl = "$($projectDef.Url)$($separator)api-version=2.0"
Write-Host "Updating Project Build number with URL: $putUrl"
Invoke-RestMethod -Method Put -Uri $putUrl -Headers $header -ContentType "application/json" -Body $projectDefJson | Out-Null
UPDATE
When I use postman to test this, I first run a get and then a put, it works...
Ok problem was with the character & which got replaced by \u0026. Added the following which solved this:
([System.Text.Encoding]::UTF8.GetBytes($projectDefJson))
So the last line becomes:
Invoke-RestMethod -Method Put -Uri $putUrl -Headers $header -ContentType "application/json" -Body ([System.Text.Encoding]::UTF8.GetBytes($projectDefJson)) | Out-Null

Running PowerShell code in powershell works, executing as .ps1 doesn't

I wrote some code which tries to Get a value from one Rest API and post it to another.
I have the code saves in a .ps1 file. If I edit it and run it (or just copy and paste it into an empty PowerShell terminal) it does what I expect. However when I try to run the same .ps1 file directly I get an error on the 2nd Invoke-RestMethod.
Don't understand why I'm getting a different result and the error message not giving me many clues.
What am I doing wrong?
The code I am using is (with modified API key):
$encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($APIkey+":"))
$headers = #{"Content-Type" = "application/json"; "AUTHORIZATION" = "Basic $encoded"}
$APIkey = "123456789"
$metricId = "123"
$r = Invoke-RestMethod -Uri https://coinbase.com/api/v1/currencies/exchange_rates
$metric = [PSCustomObject]#{
value = [Math]::Round($r.btc_to_eur, 2)
}
$baseuri = "https://api.numerousapp.com/v1/metrics/$metricId/events"
$data = ConvertTo-Json $metric
Invoke-RestMethod -Uri $baseuri -Body $data -Headers $headers -Method Post
And the error message I get when running the .ps1 file is:
Invoke-RestMethod : :
At C:\NumerousBitcoinEur.ps1:13 char:1
+ Invoke-RestMethod -Uri $baseuri -Body $data -Headers $headers -Method Post
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I'm using PowerShell 4.0
$APIkey is being set after it is being used, which must be wrong. It probably works in the console because $APIkey happens to already be set.
If you like (I think it's a good idea), you can add the following to the top of your scripts to catch errors like this one.
Set-StrictMode -Version Latest