Invoke-RESTMethod PowerShell - powershell

I am trying to use the Invoke-Restmethod to call a set of API's, but it fails with the below error, i have also posted the same json format, can some let me know what could be wrong ?
### Ignore TLS/SSL errors
add-type #"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}}
"#
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
#Create URL string for Invoke-RestMethod
$urlsend = 'https://' + 'vrslcm-01a.corp.local/lcm/api/v1/' + '/login'
#Credential
$Username = "admin#localhost"
$password = "VMware1!"
$basicAuth = "Basic " + [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("$($Username):$Password"))
$headers = #{
"description"= "Testing Authentication"
}
$body = #{
$raw= '{\n\t\"username\": \"admin#localhost\",\n\t\"password\": \"vmware\"\n}'
"mode"= $raw
}
Invoke-RestMethod -Method POST -uri $urlsend -Headers $headers -Body $body -ContentType 'application/json'
Here is the sample jSON which iam trying to invoke via powershell, it consists of the header and the body. I need to understand how we could call the same jSON POSTMAN example via the PowerShell Invoke-RestMethod
"item": [
{
"name": "authorization",
"description": "",
"item": [
{
"name": "Login",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"var response=JSON.parse(responseBody)",
"postman.setEnvironmentVariable(\"token\", response.token)"
]
}
}
],
"request": {
"url": "{{Server}}/lcm/api/v1/login",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": ""
}
],
"body": {
"mode": "raw",
"raw": "{\n\t\"username\": \"admin#localhost\",\n\t\"password\": \"vmware\"\n}"
},
"description": ""
},
"response": []
},
{
"name": "Logout",
"request": {
"url": "{{Server}}/lcm/api/v1/logout",
"method": "POST",
"header": [
{
"key": "x-xenon-auth-token",
"value": "{{token}}",
"description": ""
}
],
"body": {},
"description": ""
},
"response": []
}
]
},

make $raw to a hashtable like
$raw = #{
username=$Username
password=$Password
}
add this hashtable to the $body hashtable
$body = #{
mode= $raw
}
but now it still is a hashtable the api cannot use. thus convert it to json like
$jsonBody = $body | ConvertTo-Json
using $jsonBody should then work when used like
Invoke-RestMethod -Method POST -uri $urlsend -Headers $headers -Body $jsonBody -ContentType 'application/json'

Like the error states, the problem is your hash definition.
A null key is not allowed in a hash literal.
PowerShell tries to evaluate $raw as a hash table key. Since it hasn't been defined before it is null and fails because null is not allowed. Try it like this:
$raw= '{\n\t\"username\": \"admin#localhost\",\n\t\"password\": \"vmware\"\n}'
$body = #{
"mode"= $raw
}

Related

Graph send mail with attachment

I'm trying to send a e-mail with attachment with powershell, as soon as I add in the attachment, I get a 400 Bad Request error, while it works find without attachment. Hope someone has a clue...
Part added:
"attachments": [
{
"#odata.type": "#microsoft.graph.fileAttachment",
"name": "attachment.txt",
"contentType": "text/plain",
"contentBytes": "SGVsbG8gV29ybGQh"
}
]
Full request:
$Subject = "Subject2"
$Message = "Message2"
$Recipient = "testemailaddress"
$SaveToSentItems = $false
$Request=#"
{
"Message": {
"Subject": $(Escape-StringToJson $Subject),
"Body": {
"ContentType": "HTML",
"Content": $(Escape-StringToJson $Message)
},
"ToRecipients": [
{
"EmailAddress": {
"Address": "$Recipient"
}
}
],
"attachments": [
{
"#odata.type": "#microsoft.graph.fileAttachment",
"name": "attachment.txt",
"contentType": "text/plain",
"contentBytes": "SGVsbG8gV29ybGQh"
}
]
},
"SaveToSentItems": "$(if($SaveToSentItems){"true"}else{"false"})"
}
"#
# Convert to UTF-8 bytes
$Request_bytes = [system.Text.Encoding]::UTF8.getBytes($Request)
$headers = #{
"Authorization" = "Bearer $($attributes.EXO)"
"Accept" = "text/*, multipart/mixed, application/xml, application/json; odata.metadata=none"
"Content-Type" = "application/json; charset=utf-8"
"X-AnchorMailbox" = (Read-AADIntAccesstoken $attributes.EXO).upn
"Prefer" = 'exchange.behavior="ActivityAccess"'
}
$url="https://outlook.office.com/api/v2.0/me/sendmail"
Invoke-RestMethod -UseBasicParsing -Uri $Url -Method Post -Headers $headers -Body $Request_bytes
Error:
Invoke-RestMethod : The remote server returned an error: (400) Bad Request.
At line:47 char:1
Invoke-RestMethod -UseBasicParsing -Uri $Url -Method Post -Headers $h ...
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I use this for send attachs in mails with ms graph in powershell
$attach = "C:\file.pdf"
$fileName = (Get-Item -Path $attach).Name
$base64string = [Convert]::ToBase64String([IO.File]::ReadAllBytes($attach))
$message = '{
"message": {
"subject": "subject",
"body": {
"contentType": "HTML",
"content": "'+$body+'"
},
"importance": "high",
"toRecipients": [
{
"emailAddress": {
"address": "'+$mail+'"
}
}
],
"attachments": [
{
"#odata.type": "#microsoft.graph.fileAttachment",
"name": "'+$fileName+'",
"contentType": "text/plain",
"contentBytes": "'+$base64string+'"
}
],
},
"saveToSentItems": "true"
}'
$URL = "https://graph.microsoft.com/v1.0/users/xxxxxxxxxxxxxxxxxxxx/sendMail"
Invoke-RestMethod -Method POST -Uri $URL -Headers $headers -Body $message
Convert to Base64 string before insert in the request.
I guess you have your own "body"!
Regards.

Using POST method to SHOPIFY with Powershell

I am trying to use the following code
$uri="https://everything.myshopify.com/admin/api/202104/orders/ordernum/fulfillments.json"
$order = #{
fulfillments= {
id= 'id',
fulfillment_status="fulfilled"
}
}
$apikey = "key"
$password = "password"
$headers = #{"Authorization" = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($apikey+":"+$password))}
$body = (ConvertTo-Json $order)
$body
$file = Invoke-RestMethod -Uri $uri -Method Put -Body $body -ContentType 'application/json' -Headers $headers -UseBasicParsing
To change the fulfillment status of an order.
It is erroring however erroring with the message
Invoke-RestMethod: C:\Powershell Scripts\test.ps1:9:9 Line | 9 | $file
= Invoke-RestMethod -Uri $uri -Method Post -Body $body -Content … | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | Response status code does not indicate success: 406 (Not Acceptable).
$Body =
{
"fulfillments": {
"Attributes": [],
"File": "C:\\Powershell Scripts\\test.ps1",
"IsFilter": false,
"IsConfiguration": false,
"Module": null,
"StartPosition": {
"Content": "{\r\n id= 'id',\r\n fulfillment_status=\"fulfilled\"\r\n }",
"Type": 19,
"Start": 140,
"Length": 78,
"StartLine": 3,
"StartColumn": 19,
"EndLine": 6,
"EndColumn": 6
},
"DebuggerHidden": false,
"Id": "6d564632-241c-4644-8ffd-8cb9c1a76daa",
"Ast": {
"Attributes": "",
"UsingStatements": "",
"ParamBlock": null,
"BeginBlock": null,
"ProcessBlock": null,
"EndBlock": "id= 'id',\r\n fulfillment_status=\"fulfilled\"",
"DynamicParamBlock": null,
"ScriptRequirements": null,
"Extent": "{\r\n id= 'id',\r\n fulfillment_status=\"fulfilled\"\r\n }",
"Parent": "{\r\n id= 'id',\r\n fulfillment_status=\"fulfilled\"\r\n }"
}
}
}
Any help appreciated

How to provide the json request body in azure powershell script task

Hi I am running REST API call using the powershell task in Azure pipeline, how do i pass the $body value to the below API endpoint
Invoke-RestMethod -Uri $uri -Method Post -ContentType "application/json" -Headers $header -Body $body
Reference of the below request body,
It seems you are trying to move a file, check the sample below:
Param(
[string]$organisation = "organisation",
[string]$repositoryId = "f2aa1d87-xxxx-48df-xxxx-6505ffxxxxf9",
[string]$keepForever = "true",
[string]$user = "user",
[string]$token = "token" )
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
$postresults = "https://dev.azure.com/$organisation/_apis/git/repositories/$repositoryId/pushes?api-version=6.0"
$body = '{
"refUpdates": [
{
"name": "refs/heads/master",
"oldObjectId": "6e3c1f07d12eaf805a16db1352771816148c24b5"
}
],
"commits": [
{
"comment": "Moving activetasks.md to a new folder.",
"changes": [
{
"changeType": "rename",
"sourceServerItem": "/activetasks.md",
"item": {
"path": "/tasks/content/activetasks.md"
}
}
]
}
]
}'
$result = Invoke-RestMethod -Uri $postresults -Method Post -Body $body -ContentType "application/json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}

Format for json via powershell

I'm trying to use powershell to send json to DevOps API. I can't seem to figure out how to properly format this so powershell will take it. I keep getting this error. Any advice? I'm able to use the same json in Postman without any issues. Thanks
$URI= "https://vsaex.dev.azure.com/$ClientOrg/_apis/userentitlements?api-version=5.1-preview.2" $AzureDevOpsAuthenicationHeader = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($PAT)")) }
Invoke-RestMethod -uri $URI -Method POST -Headers $AzureDevOpsAuthenicationHeader -Body $a -ContentType "application/json"
$a= ConvertFrom-JSON #'
{
"accessLevel": {
"licensingSource": "msdn",
"accountLicenseType": "enterprise",
"msdnLicenseType": "enterprise"
},
"extensions": [
{
"id": "ms.feed"
}
],
"user": {
"principalName": "email#mail.com",
"subjectKind": "user"
},
"projectEntitlements": [
{
"group": {
"groupType": "projectAdministrator"
},
"projectRef": {
"id": "0685a10e"
}
}
]
}
'#
Invoke-RestMethod : {"$id":"1","innerException":null,"message":"Value cannot be null.\r\nParameter name: userEntitlement","typeName":"System.ArgumentNullException,
mscorlib","typeKey":"ArgumentNullException","errorCode":0,"eventId":0}
At line:4 char:1
+ Invoke-RestMethod -uri $URI -Method POST -Headers $AzureDevOpsAutheni ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Your body should be the JSON string itself and not an object built from the JSON.
$a= #'
{
"accessLevel": {
"licensingSource": "msdn",
"accountLicenseType": "enterprise",
"msdnLicenseType": "enterprise"
},
"extensions": [
{
"id": "ms.feed"
}
],
"user": {
"principalName": "email#mail.com",
"subjectKind": "user"
},
"projectEntitlements": [
{
"group": {
"groupType": "projectAdministrator"
},
"projectRef": {
"id": "0685a10e"
}
}
]
}
'#
Invoke-RestMethod -uri $URI -Method POST -Headers $AzureDevOpsAuthenicationHeader -Body $a -ContentType "application/json"

Read json value from the http response trigger by invoke-webrequest

I am trying to fetch a particular value from the JSON response of an invoke-web request. But the value is not capturing
Tried using the following script, where the $body contains the response.
$url = "http://localhost:9096/getMachineStatus"
$HTTP_Request = [System.Net.WebRequest]::Create($url)
$HTTP_Response = $HTTP_Request.GetResponse()
$HTTP_Status = [int]$HTTP_Response.StatusCode
$body = Invoke-WebRequest -Uri $url
The response of the above script:
{
"Name": "LocalTestMachine",
"Profile": "QA",
"Stacks": [
{
"Region": "Mumbai-1",
"State": "Stopped",
"StackName": "QA",
"StackCreationStatus": "CREATE_Success",
"Instances": [
{
"MachineName": "LocalMachine",
"IpAddress": "10.10.10.164",
"State": "stopped",
"InstanceId": "i-0777e90151b22da44",
"ImageId": "ami-0322ff2d8d099g56c",
"CustomImageName": "ubuntu-trusty-16.04",
"InstanceType": "m4.large",
"LaunchTime": "2019-09-04T02:42:36-04:00",
"AvailabilityZone": "Mumbai-1",
"Tags": [
{
"Key": "ProductLine",
"Value": "Cloud"
}]
}]
}]
}
I just want to retrieve the value associated with the object State which is Stopped.
I tried with
$currentVMState = $body | where {$_.State}
It is not working
To get the value of the first State item in the Stacks array, do this:
$json = $body | ConvertFrom-Json
$json.Stacks[0].State
returns
Stopped
First you need to convert the response to json:
$json = $body | ConvertFrom-Json
Then iterate the $json object to get the state value:
$json.stacks.instances | ForEach-Object { $_.State }