Invoke-RestMethod with PowerShell - rest

I am trying to post data to a URL using PowerShells Invoke-RestMethod however I constantly keep getting this message:
+ $response.RawContent​
+ ~
Unexpected token '​' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
Am I missing an escape of a string literal somewhere or malformed quote mark?
$user = "username"
$pass = "password"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user, $pass)))
$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')
$uri = "http://myurl.com"
$params = #{
message = "hello world"
}
$response = Invoke-RestMethod -Method Post -Headers $headers -Uri $uri -Body $params
$response.RawContent​

Removed $response.RawContent and it works. Changed it to echo $response to see output.

Related

CURL -F file push -> convert to equivalent PowerShell Invoke-RestMethod

I have seen a ton of attempts to do this in Stack Overflow, but none of the approaches have worked for me (and many others). But it seems like a simple thing to do:
This curl command works fine in powershell.
function curlPush() {
$url = "$post_url/$dset_id/transactions/$trid"
$header = "Authorization: Bearer $token"
curl.exe --request POST --url $url --header $header -F file="#$folder_path"
}
However the equivalent using Invoke-RestMethod gives an error:
function pushFile() {
$url = "$post_url/$dset_id/transactions/$trid"
$header = #{
'Authorization' = "Bearer $token"
'Content-Type' = 'multipart/form-data'
}
$response = Invoke-RestMethod -Uri $url -header $header -Method POST -InFile $folder_path
if (!$?) {
Write-Host $_.ErrorDetails.Message
}
$response
}
The error returned is:
Invoke-RestMethod : {"errorCode":"INVALID_ARGUMENT","errorName":"Default:InvalidArgument","errorInstanceId":"0bc80c74-35ae-4837-a87e-ff0e214b451b","parameters":{}}
At C:\Users\Documents\Software Projects\SolarWinds\PushFiles.ps1:42 char:17
+ ... $response = Invoke-RestMethod -Uri $url -header $header -Method POST ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Any suggestions?

Trying to use a azure Test Plan api to add tester name in Test suite from power shell script

$UpdateTesterNameUri = "https://dev.azure.com/MyOrg/MyProj/_apis/test/Plans/" + $Id + "/Suites/121221/points/" + $node + "?api-version=6.0"
Write-Output $UpdateTesterNameUri
$testerNameBody =
#{
tester = #{
"displayName" = "Veeresh Kokkalla "
}
}
$testerName = $testerNameBody | ConvertTo-Json
Invoke-RestMethod -Uri $UpdateTesterNameUri -Headers $headers -Method Patch -Body $testerName -ContentType 'application/json'
Getting following issue
Invoke-RestMethod : {"$id":"1","innerException":null,"message":"Value cannot be null.\r\nParameter name: tester","typeName":"System.ArgumentNullException,
mscorlib","typeKey":"ArgumentNullException","errorCode":0,"eventId":0}
At C:\Users\v-vkokkalla\Downloads\ReleaseTrain - Dailymveeresh.ps1:173 char:13
+ Invoke-RestMethod -Uri $UpdateTesterNameUri -Headers $hea ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
When I put debug it shows tester has values.
From your PowerShell sample, you need to define the userID in the request body. Then you can update the tester of the test point.
Here is an PowerShell example:
$token = "PAT"
$url="https://dev.azure.com/org/project/_apis/testplan/Plans/TestPlanID/Suites/TestSuiteID/TestPoint?includePointDetails=true&returnIdentityRef=true&api-version=6.0"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$JSON = #"
[
{
"id":Testpointid,
"tester":
{
"id":"userid",
"displayName":"xx"
}
}
]
"#
$response = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic $token"} -Method Patch -ContentType application/json -Body $JSON
Write-Host "$response"

Unable to ingest JSON stream data to Azure Event Hub

I would like to post the JSON results which I am getting from an API endpoint to the Azure Event Hub $default consumer group but I am getting the below error:
Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.
At H:\Users\User1 - scripts\get_mel_streetparking_data.ps1:34 char:1
+ Invoke-RestMethod -Uri $URI -Method $method -Headers $headers -Body $res ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke- RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I wrote the below piece of powershell script where the following piece of get code runs fine:
$url = "https://data.melbourne.vic.gov.au/resource/vh2v-4nfs"
$apptoken = "abcdasdadaaf"
# Set header to accept JSON
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Accept","application/json")
$headers.Add("X-App-Token",$apptoken)
$results = Invoke-RestMethod -Uri $url -Method get -Headers $headers
but below piece of code fails with the above given error:
$method = "POST"
$URI = "https://[servicebusNamespace].servicebus.windows.net/[eventHubPath]/messages"
$signature = "SharedAccessSignature sr=[servicebusNamespace].servicebus.windows.net%2feventhub- streetparking&sig=%3dgZfDHEGN8lVEGgqu4N64TW70BLuSKARSKgMPeRByc%5d&se=604985&skn=RootManageSharedAccessKe"
# API headers
$headers = #{
"Authorization"=$signature;
"Content-Type"="application/json";
}
# create Request Body
#$body = "$results"
# execute the Azure REST API
Invoke-RestMethod -Uri $URI -Method $method -Headers $headers -Body $results
I generated SAS token with the help of the below code:
[Reflection.Assembly]::LoadWithPartialName("System.Web")| out-null
$URI="[servicebusNamespace].servicebus.windows.net/[eventHubPath]"
$Access_Policy_Name="RootManageSharedAccessKey"
$Access_Policy_Key="Root key value"
#Token expires now+3000
$Expires=([DateTimeOffset]::Now.ToUnixTimeSeconds())+3000
$SignatureString=[System.Web.HttpUtility]::UrlEncode($URI)+ "`n" + [string]$Expires
$HMAC = New-Object System.Security.Cryptography.HMACSHA256
$HMAC.key = [Text.Encoding]::ASCII.GetBytes($Access_Policy_Key)
$Signature = $HMAC.ComputeHash([Text.Encoding]::ASCII.GetBytes($SignatureString))
$Signature = [Convert]::ToBase64String($Signature)
$SASToken = "SharedAccessSignature sr=" + [System.Web.HttpUtility]::UrlEncode($URI) + "&sig=" + [System.Web.HttpUtility]::UrlEncode($Signature) + "&se=" + $Expires + "&skn=" + $Access_Policy_Name
$SASToken
Please help me why am I seeing unauthorized error
It was my bad that I did not replace the below values before the SAS token generation.
$Access_Policy_Name="RootManageSharedAccessKey"
$Access_Policy_Key="Root key value"

POST method in powershell gives 405 error

I have a POST method that works fine in Postman but I can't get it working in powershell.
The client id and client secret are setup in AWS cognito.
I am using basic authentication to retrieve the access token.
Below is my code,
$encodedlogin="MNBvbmZfYWsxUTRocG1qOG5zOGZqZ8xvN646a1plMDNsMTZjY6xucTA5MzVkOGg2aGdlaG1mdXAxaHZkMmlxaXY0PKOdM3BcxNBtPLs5"
$authorisation = "Basic " + $encodedlogin
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization",$authorisation)
$headers.Add("Accept","application/json")
$headers.Add("Content-Type","application/json")
$headers.Add("ResponseType","id_token")
$body = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$body.Add("grant_type","client_credentials")
$body.Add("scope","cybergate-gateway-resources/cybertron.fullaccess")
$uri = "https://cybergate.auth.eu-west-2.amazoncognito.com/oauth2/token"
$response = Invoke-WebRequest -Uri $uri -Headers $headers -body $body -Method Post -ContentType "application/json"
The error as follows,
Invoke-WebRequest : The remote server returned an error: (405) Method Not Allowed.
At C:\CyberGate\src\CyberGate.API\Scripts\Deploy\CyberGate.ps1:33 char:17
+ ... $response = Invoke-WebRequest -Uri $uri -Headers $headers -body $body ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
Any ideas?
Thanks

Invoke-WebRequest error: no parameter like "-form"

for some reason I got stuck with an simple Invoke-WebRequest. I need to send an XML-File to a website by Method "POST" and enc-Type "multipart/form-data". My code:
$SupraliftXML="C:\supralift.xml"
$Uri = 'https://www.supralift.com/servlet/EcutServlet?handler=BulkloadHandler&jfaction=0'
$Form = #{
muddledPassword = 'mypassword'
userID = 'myuserID'
XMLfile = Get-Item -Path $SupraliftXML
}
$Result = Invoke-RestMethod -AllowUnencryptedAuthentication -Uri $Uri -Method Post -Form $Form
I got an error that there is no parameter like "-form"
$Result = Invoke-WebRequest -Uri $Uri -Method Post -Form $Form
+ CategoryInfo : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
Thank you for any help!