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"
Related
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.
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
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)}
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
}
I want to index data from PowerShell into Elasticsearch.
The data from the variable:
$var1=Get-Process|Select-Object CPU | ConvertTo-Json
$var1 output:
[
{
"CPU": 11.265625
},
{
"CPU": 0.09375
},
{
"CPU": 13.796875
},
{
"CPU": 0.109375
},
{
"CPU": 0.953125
},
{
"CPU": 624.65625
},
{
"CPU": 3.96875
},
{
"CPU": 0.046875
},
{
"CPU": 1.15625
},
{
"CPU": 0.125
},
{
"CPU": 0.625
},
{
"CPU": 0.65625
},
{
"CPU": 0.109375
}
]
I am attempting to load data with a command:
Invoke-WebRequest -ContentType 'application/json' -Method POST `
-Uri 'http://localhost:9200/123456789/doc' `
-Body ([System.Text.Encoding]::UTF8.GetBytes($var1)) -UseBasicParsing
or
Invoke-WebRequest -ContentType 'application/json' -Method POST `
-Uri 'http://localhost:9200:9200/123456789/doc' `
-Body $var1 -UseBasicParsing
I get the error message:
Invoke-WebRequest : {"error":{"root_cause":[{"type":"not_x_content_exception","reason":"not_x_content_exception: Compressor detection can only be called on some xcontent bytes or compressed xcontent
bytes"}],"type":"mapper_parsing_exception","reason":"failed to parse","caused_by":{"type":"not_x_content_exception","reason":"not_x_content_exception: Compressor detection can only be called on some xcontent bytes or compressed xcontent
bytes"}},"status":400}
At line:1 char:1
+ Invoke-WebRequest -ContentType 'application/json' -Method POST `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
Does anyone know how to make it work within the PowerShell environment?
My Powershell version is:
PS C:\> $PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
5 1 15063 1387
I believe it might be related to the JSON syntax.