Multform data for Invoke-Restmethod giving 405 Powershell - powershell

Below is the curl command which i translated in to Powershell but when i execute it i get 405, can any one help
curl --location --request POST 'https://anypoint.com/hybrid/api/v1/applications' \
--header 'X-ANYPNT-ENV-ID: 4a961b64' \
--header 'X-ANYPNT-ORG-ID: c6589234ad' \
--header 'Authorization: Bearer c83605e456432e6' \
--form 'artifactName="TEST-DEVOPS-SC"' \
--form 'targetId="12073594"' \
--form 'application="{\"configuration\":{}}"' \
--form 'file=#"/C:/Users/vada/Downloads/documents-v1-1.0.2.application.jar"'
Powershell
$Headers = #{
'Authorization' = "Bearer $($Token.access_token)"
'X-ANYPNT-ENV-ID' = '4a96ab37cf1b64'
'X-ANYPNT-ORG-ID' = 'c658379234ad'
}
Write-Host $Headers.Authorization
$path = "E:\actionsdocuments\documents\target\documents-v1-1.0.2-application.jar";
$file_name=$path.split('\')[-1]
$domain_id= 11312492
$Uri = "https://anypoint.com/hybrid/api/v1/applications/$domain_id"
$fileBytes = [System.IO.File]::ReadAllBytes($path);
$fileEnc = [System.Text.Encoding]::GetEncoding('ISO-8859-1').GetString($fileBytes);
#$jsonfile = [System.IO.File]::ReadAllBytes($jsonpath)
#$jsonEnc = [System.Text.Encoding]::GetEncoding('ISO-8859-1').GetString($jsonfile);
$boundary = [System.Guid]::NewGuid().ToString();
$LF = "`r`n";
$bodyLines = (
"--$boundary",
"Content-Disposition: form-data; name=`"artifactName`"$LF",
"TEST-DEVOPS-ONPREM$LF",
"--$boundary",
"Content-Disposition: form-data; name=`"targetId`"$LF",
"12073594$LF",
"--$boundary",
"Content-Disposition: form-data; name=`"application`"$LF",
"{`"configuration`":{}}$LF",
"--$boundary",
"Content-Disposition: form-data; name=`"file`"; filename=`"$file_name`"",
"Content-Type: application/octet-stream$LF",
$fileEnc,
"--$boundary--$LF"
) -join $LF
$response= Invoke-RestMethod -Uri $Uri -Headers $Headers -Method POST -ContentType "multipart/form-data; boundary=`"$boundary`"" -Body $bodyLines
Error
Invoke-RestMethod : {"message":"HTTP 405 Method Not Allowed"}
At line:63 char:12
$response= Invoke-RestMethod -Uri $Uri -Headers $Headers -Method POST ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Related

Convert HTTP request to Powershell and cURL

I'm trying to convert a HTTP request (which I've never dealt with before) into a cURL and Powershell command, but I'm not getting anywhere....can someone help me fill in the blanks?
POST /api/users.profile.set
Host: slack.com
Content-type: application/json; charset=utf-8
Authorization: bearer_token
{
"profile": {
"status_text": "Eating some french fries from the frituur",
"status_emoji": ":fries:"
}
}
curl 'https://slack.com/api/users.profile.set' `
--header 'Authorization: bearer_token' `
--header 'Content-Type: application/json' `
--data-raw "{
\"profile\": {
\"status_text\": \"On Lunch\",
\"status_emoji\": \":hamburger:\"
}
}"
and
Invoke-WebRequest -Headers #{"Authorization" = "bearer_token"} `
-Method POST `
-Uri https://slack.com/api/users.profile.set `
-ContentType application/json
Fixed it myself.
curl -X POST 'https://slack.com/api/users.profile.set' `
-H 'Authorization: Bearer xoxp-xxxxxxxxxxxxxxxxx' `
-H 'Content-Type: application/json; charset=utf-8' `
-d '{
\"profile\": {
\"status_text\": \"Sick\",
\"status_emoji\": \":sickpepe:\",
\"status_expiration\": \"480\"
}
}'
$body = #{
profile = #{
status_text = "Eating some french fries from the frituur"
status_emoji = ":fries:"
status_expiration = 60
}
}
Invoke-WebRequest -Headers #{"Authorization" = "Bearer xoxp-xxxxxxxxxxxxxxxxxxxx"} `
-Method POST `
-Uri https://slack.com/api/users.profile.set `
-ContentType 'application/json; charset=utf-8' `
-Body ($body|ConvertTo-Json)
```

Convert dataurlencoded curl command to powershell alterntive {"error":"invalid_request","error_description":"Invalid grant_type"}

I need help with converting data-urlencoded curl command to powershell
Any help would be highly appreciated
curl --location --request POST https://anypoint.muloft.com/accounts/api/v2/oauth2/token --header 'Content-Type:application/x-www-form-urlencoded' --data-urlencode 'client_id=44b1d81330084afbb39c74' --data-urlencode 'client_secret=c38042cda4FD6af9fc18' --data-urlencode 'grant_type=client_credentials'
I tried this but i am getting
$contentType = 'application/x-www-form-urlencoded'
PS C:\Users\mation> Invoke-WebRequest -Uri ("https://anypoint.muloft.com/accounts/api/v2/oauth2/token") -ContentType $contentType -Method Post -Body { client_id="44b1d81330039c74" ;client_secret = "c38042cE3D6af9fc18" ; grant_type= "authorization_code" }
Invoke-WebRequest : {"error":"invalid_request","error_description":"Invalid grant_type"}
At line:1 char:1
+ Invoke-WebRequest -Uri ("https://anypoint.mulesoft.com/accounts/api/v ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
Below is what worked for me
$RequestAccessTokenUri = "https://anypoint.muloft.com/accounts/api/v2/oauth2/token"
$ClientId = "44b1d8bb39c74"
$ClientSecret = "c380f9fc18"
$body = "grant_type=client_credentials&client_id=$ClientId&client_secret=$ClientSecret"
$Token = Invoke-RestMethod -Method Post -Uri $RequestAccessTokenUri -Body $body -ContentType 'application/x-www-form-urlencoded'

Curl To Powershell - Click Send

I am struggling with this code as I have never encountered
Here is the Example code that click send provides.
curl --include \
--header "Authorization: Basic YXBpLXVzZXJuYW1lOmFwaS1wYXNzd29yZA==" \
--request POST \
--header "Content-Type: application/x-www-form-urlencoded" \
--data-binary "username=myusername&key=1234-I3U2RN34IU-43UNG&to=61411111111,64122222222,61433333333&senderid=example&message=testing" \
'https://api-mapper.clicksend.com/http/v2/send.php'
URL: https://developers.clicksend.com/docs/http/v2/#send-an-sms
Here is what I have figured out so far:
$BaseURL = "https://api-mapper.clicksend.com/http/v2/send.php"
$Header = #{
"Authorization" = "Basic"+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$APIKey"))
}
$body = #{
"useranme"="$Username"
"key"="$APIKey"
"to"="$To"
"senderid"="$from"
"message"=$Message
}
$Return = Invoke-RestMethod -Method Post -Headers $Header -ContentType "application/x-www-form-urlencoded" -Uri $BaseURL -Body $body
$return.InnerXml
I'm stuck on the --data-binary part of the code.
I believe using the --data-binary in curl is like creating a string in the body of the request:
$BaseURL = "https://api-mapper.clicksend.com/http/v2/send.php"
$Username = "Username"
$APIKey = "SomeAPIKey"
$To = "Recipient"
$From = "Sender"
$Message = "MessageFoRecipient"
$Header = #{
"Authorization" = "Basic"+ " " + ([System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$APIKey")))
}
$body = "username=$Username" + "&" + "key=$APIKey" + "&" + "to=$To" + "&" + "senderid=$From" + "&" + "message=$Message"
$return = Invoke-RestMethod -Method Post -Headers $Header -ContentType "application/x-www-form-urlencoded" -Uri $BaseURL -Body $body
$return.InnerXml
Invoke-RestMethod assumes that you want your POST body to be application/x-www-form-urlencoded (unless otherwise specified, e.g. XML, JSON).  You must be having an issue with something such as the fact that the Authorization header doesn't have a space between Basic and the Base64 string, or the fact that username has a typo.
$BaseURL = 'http://localhost:8000'
$Username = 'api-username'
$ApiKey = 'api-password'
$To = '61411111111,64122222222,61433333333'
$From = 'example'
$Message = 'testing'
$SenderId = 'example'
$Body = #{
username = $Username
key = $ApiKey
to = $To
senderid = $SenderId
message = $Message
}
$Header = #{
Authorization = 'Basic ' + ([System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$APIKey")))
}
$Return = Invoke-RestMethod -Method Post -Headers $Header -Uri $BaseURL -Body $Body
$Return.InnerXml
Yields the following HTTP request:
POST / HTTP/1.1
Host: localhost:8000
Authorization: Basic YXBpLXBhc3N3b3Jk
User-Agent: Mozilla/5.0 (Windows NT 10.0; Microsoft Windows 10.0.19042; en-US) PowerShell/7.2.1
Content-Length: 112
Content-Type: application/x-www-form-urlencoded
key=api-password&message=testing&username=api-username&to=61411111111%2C64122222222%2C61433333333&sender=example

Upload document to Salesforce using powershell

I'm trying to upload a text file in our Salesforce application using PowerShell.
The curl code which I'm trying to mimic in PowerShell is:
curl -X POST -H "Authorization: {SESSION_ID}" \
-H "Content-Type: multipart/form-data" \
-F file=#document.txt \
-F "name__v=myDocument" \
-F "type__v=Undefined" \
-F "lifecycle__v=Unclassified" \
https://{server}/api/{version}/objects/documents
Here is the PowerShell code which I have written taking hint from the web:
$URL="https://{server}/api/{version}/auth"
$CT="application/x-www-form-urlencoded"
$User="user"
$Password="pass"
$SessionID=(Invoke-RestMethod -Method Post -Uri $URL -Body #{"Content-Type" = $CT; "username" = $User; "password" = $Password}).sessionId
$URL="https://{server}/api/{version}/objects/documents"
$boundary=[System.Guid]::NewGuid().ToString()
$LF="`r`n"
$File=Get-Content("....\test.txt")
$fileBin=[System.IO.File]::ReadAllBytes("....\test.txt")
$enc=[System.Text.Encoding]::GetEncoding("iso-8859-1")
$fileEnc=$enc.GetString($fileBin)
$Body1=(
"--$boundary",
"Content-Disposition: form-data; name__v=`"kaz.txt`"; type__v=`"Undefined`"; lifecycle__v=`"Unclassified`"",
"Content-Type: application/octet-stream$LF",
$fileEnc,
"--$boundary--$LF"
) -join $LF
$Body2 = (
"file=$File; name__v=`"kaz.txt`"; type__v=`"Undefined`"; lifecycle__v=`"Unclassified`""
)
Invoke-RestMethod -Method POST -Uri $URL -Headers #{"Authorization" = $SessionID; "Content-Type" = "multipart/form-data; boundary=`"$boundary`""} -Body $Body1
Invoke-RestMethod -Method POST -Uri $URL -Headers #{"Authorization" = $SessionID; "Content-Type" = "multipart/form-data; boundary=`"$boundary`""} -Body $Body2
None of these are working and I'm getting error
PARAMETER_REQUIRED lifecycle__v: Missing required parameter : lifecycle__v.
I modified the body and now its working fine
$Body = (
"--$boundary", "Content-Disposition: form-data; name=`"file`"; filename=`"test.docx`"", "Content-Type: application/octet-stream$LF", $fileEnc,
"--$boundary", "Content-Disposition: form-data; name=`"lifecycle__v`"", "", "Unclassified",
"--$boundary", "Content-Disposition: form-data; name=`"type__v`"", "", "Undefined",
"--$boundary--"
)-join $LF
Invoke-RestMethod -Method POST -Uri $URL -Headers #{"Authorization" = $SessionID; "Content-Type" = "multipart/form-data; boundary=$boundary"} -Body $Body

Need help translating Curl statement to Powershell

I'm trying to rewrite the following curl code: (note I've used OBSCURED to conceal secrets)
curl -H "Content-Type: application/json" \
-H "Authorization: Bearer OBSCURED" \
-X POST \
-d "{\"color\": \"pink\", \"message\": \"OBSCURED\" }" \
https://OBSCURED
into something I can use in Powershell but I'm running into a lot of grief.. this is my attempt so far:
$body = #{
color = "pink"
message = "OBSCURED"
}
Invoke-WebRequest -ContentType application/json -Headers #{"Authorization" = "Bearer OBSCURED"} -Method Post -Body "$body" -Uri https://OBSCURED
But I'm running into this powershell error:
Invoke-WebRequest : The remote server returned an error: (405) Method Not Allowed.At E:\BuildAgent\temp\buildTmp\powershell2561816976397359486.ps1:16 char:1
Invoke-WebRequest -Headers #{"Authorization" = "Bearer OBSCURED ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
I cannot test this now, but I believe you need to submit JSON as body, so you might try converting your body to JSON first with convertto-JSON and then try posting:
$bodyJSON = body |convertto-JSON
then call:
Invoke-WebRequest -ContentType application/json -Headers #{"Authorization" = "Bearer OBSCURED"} -Method Post -Body $bodyJSON -Uri https://OBSCURED