Remote server Run CMD in Powershell - powershell

I am trying to upload a Zip file via RestAPI in powershell and Powershell version I am using is 5.1.
since Invoke-restmethod in powershell 5.1 doesn't have -form option,I tried to run curl command in CMD using powershell.When I run it locally it's working correctly. But when i try to run it in a server(azure devops agent) I am getting error saying curl command is not recognized.
What am i missing here it's runs as expected when i try in vs code, but not when i run it from a server.
$header1 = "accept: application/json"
$header2 = "X-Authorization: $($token)"
$header3 = "Content-Type: multipart/form-data"
$body1 = "upload=#Name.zip;type=application/x-zip-compressed"
$body2 = "actionIfExisting=Existing"
$body3 = "publicWorkspace=Public"
cmd.exe /c curl -X POST $uri -H $header1 -H $header2 -H $header3 -F $body1 -F $body2 -F $body3

Luckily I had git installed in the server and I read in this stack overflow page that Git comes with preInstalled curl.exe. So I called the path where git has curl.exe and using & operator in powershell to execute the curl.exe directly in powershell itself.
& 'C:\users\git\mingw64\bin\curl.exe' -X POST $uri -H $header1 -H $header2 -H $header3 -F $body1 -F $body2 -F $body3

Related

Convert Powershell command to curl

I am trying make the following API calls with a curl command and run it on Linux:
https://octopus.com/blog/manually-push-build-information-to-octopus
This what I got:
curl -X POST https://YourServerUrl -H "X-Octopus-ApiKey"="API-XXXXXXXXXXXXXXXXXXXXXXXXXX" -H "Content-Type: application/json" -d "#jsonBody"
I am not sure how to convert this script to a json in curl
$jsonBody = #{
PackageId = "twerthi/xCertificatePermission"
Version = "1.0.0"
OctopusBuildInformation =
#{
BuildEnvironment = "Jenkins"
VcsCommitNumber = "2350881a389517288b31432d469c5c4199a1fba9"
VcsType = "Git"
VcsRoot = "https://github.com/twerthi/xCertificatePermission.git"
}
} | ConvertTo-Json -Depth 10
The curl command -d (--data) is the specified data in the POST request. So you should be able to just enter valid JSON data as part of the call. i.e. something like this:
curl -X POST https://YourServerUrl -H "X-Octopus-ApiKey"="API-XXX" -H "Content-Type: application/json" -d '{ "PackageId":"twerthi/xCertificatePermission", "Version":"1.0.0", "OctopusBuildInformation":{ "BuildEnvironment":"Jenkins", "VcsCommitNumber":"2350881a389517288b31432d469c5c4199a1fba9", "VcsType":"Git", "VcsRoot":"https://github.com/twerthi/xCertificatePermission.git"}}'
Note, if you are testing this in cmd/bash etc, you can split the command over multiple lines by using an escape character. Windows: ^ Linux/MacOS: \
Example in Windows:
curl -X POST https://YourServerUrl ^
-H "X-Octopus-ApiKey"="API-XXX" ^
etc....
Also, assuming that's valid PS, you can just run it and check the result in $jsonBody to see how its formatted.
Assuming you want to call the external curl utility from PowerShell (note that on Windows, in Windows PowerShell, you'll have to call it as curl.exe):
curl -X POST https://YourServerUrl `
-H 'X-Octopus-ApiKey: API-XXXXXXXXXXXXXXXXXXXXXXXXXX' `
-H 'Content-Type: application/json' `
-d ($jsonBody -replace '([\\]*)"', '$1$1\"')
Note the unfortunate need for a -replace operation on the $jsonBody variable containing your JSON string, which - as of PowerShell 7.1 - is needed to work around a long-standing bug, discussed in this answer.

Converting Curl command to Powershell invoke rest-method

Does anyone know how to convert this Curl command to PowerShell invoke rest-method. Using PowerShell version 5.1.
curl -vqgsSkH "Content-Type: multipart/form-data" --no-progress-bar --header "X-FeApi-Token: "Tokenn string"=" -F "filename=#C:\Users\User\Documents\all.csv" -F "options={\"application\":\"2\",\"timeout\":\"500\",\"priority\":\"0\", \"profiles\":[\"win7-sp1\"],\"analysistype\":\"1\",\"force\":\"true\", \"prefetch\":\"0\"}" https://<URL>:443/wsapis/v2.0.0/submissions/file

Curl POST gitlab API gives 404

I am trying to push a file to my folder called "collections" in my repository using curl.
I've spent almost 2 days investigating problem and I am not sure what is the exact problem.
curl -D- -k -X GET -H "PRIVATE-TOKEN: faNFKoC4-opiDJ0FJSk" https://gitlab.example.com/api/v4/projects/592/repository/tree?path=collections
Get request works properly and I get list of files in collections folder.
The collections folder is a folder in my gitlab repository
But when I try to POST a file to that exact same folder I get 404:
curl -D- -k -X POST -H "PRIVATE-TOKEN: faNFKoC4-opiDJ0FJSk" -F "file=#C:/Documents/Folder_A/bp30_QA.csv" https://gitlab.example.com/api/v4/projects/592/repository/tree?path=collections
Am I missing some parameter? also gitlab API didn't help me very much.
Edit: Solution from Bertrand Martel helped me solve the issue
Also for everyone on windows having trouble installing jq
jq is a lightweight and flexible command-line JSON processor.
Install choco: https://chocolatey.org/install
Open powershell as administrator and run:
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
After installation, run:
choco install jq
To create a new file called bp30_QA.csv in the collections folder, you can use the following :
curl -H 'PRIVATE-TOKEN: YOUR_PRIVATE_TOKEN' \
-H "Content-Type: application/json" \
-d '{
"branch": "master",
"author_email": "johndoe#gmail.com",
"author_name": "John Doe",
"content": '"$(jq -Rs '.' bp30_QA.csv)"',
"commit_message": "create a new file"
}' "https://gitlab.com/api/v4/projects/592/repository/files/collections%2Fbp30_QA.csv"
It uses jq to wrap the content of the file in a single JSON field (check this post)

Bad request when calling rest api using curl or Invoke-RestMethod

I want to convert speech to text using Microsoft speech-to-text service from within a bash script or PowerShell script. I tried using curl (Git bash) and Invoke-RestMethod (PowerShell) to send my 16 bit pcm mono wav audio file to the stt service.
The service is working, I used a c# example provided by Microsoft to test it. With the c# example I'm able to send the audio file and receive the text from the stt services.
Now I wanted to do this in a script.
Using curl in Git Bash:
curl -X POST "https://westus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US&format=detailed" \
-H "Ocp-Apim-Subscription-Key: <my_subscription_key>" \
-H "Content-Type: audio/wav; codecs=audio/pcm; samplerate=16000" \
--data-binary audio.wav
Insufficient data to detect audio format: 7 bytes
Even using -d or --data or --data-raw instead of --data-binary doesn't change anything.
Using Invoke-RestMethod in PowerShell:
$audioBytes = [System.IO.File]::ReadAllBytes("c:\full\path\to\aduio\file.wav")
Invoke-RestMethod `
-Method Post `
-Uri "https://westeurope.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US&format=detailed" `
-Headers #{'Ocp-Apim-Subscription-Key' = '<my_subscription_key>'} `
-ContentType 'audio/wav; codecs=audio/pcm; samplerate=16000' `
-Body $audioBytes
Invoke-RestMethod: The remote server returned an error: (400) Bad Request.
Same error using -InFile audio.wav instead of -Body $audioBytes.
Am I missing something? Is there an error which I don't see?

Calling an PingAccess APIs from Powershell

I am trying to call PingAccess APIs to configure my PingAccess.
I am new to using APIs to do this, and have a question.
I am trying to use CURL to the API .
curl -k -u Administrator:dummypsswd -H "X-Xsrf-Header: PingAccess" -H "Content-Type: application/json" -d '{"alias":"PLACEHOLDER_STAR_MINGLE","fileData": [[System.IO.File]::ReadAllBytes("C:\test.pfx")],"password": "1234"}' https://localhost:9000/pa-admin-api/v1/keyPairs/import -v
When I run this I get the following error.
I still dont know why am I unauthorized. Any help is appreciated.
When you have special characters in your password you'll need to enclose the username/password tuple in double quotes:
curl -k -u "Administrator:dummypsswdwithspecialcharslike&&" -H "X-Xsrf-Header: PingAccess" -H "Content-Type: application/json" -d '{"alias":"PLACEHOLDER_STAR_MINGLE","fileData": [[System.IO.File]::ReadAllBytes("C:\test.pfx")],"password": "1234"}' https://localhost:9000/pa-admin-api/v1/keyPairs/import -v