Problem with cURL to Powershell conversion - powershell

I have been trying to convert the below cURL command to PowerShell so that I can use it on my script. I converted it but, every time I execute the command, it gives me error like in the screenshot.
cURL command: curl -X POST "https://www.hybrid-analysis.com/api/v2/quick-scan/file?_timestamp=1585901455112" -H "accept: application/json" -H "user-agent: API_KEY" -H "Content-Type: multipart/form-data" -F "scan_type=all" -F "file=#xyz.png;type=image/png" -F "no_share_third_party=false" -F "allow_community_access=false"
converted powershell command:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;
$fileqq = Get-ChildItem -Path "C:\temp\xyz.jpg"
Invoke-WebRequest "https://www.hybrid-analysis.com/api/v2/quick-scan/file" -Headers #{'accept' = 'application/json'; 'user-agent' = 'Falcon Sandbox' ; 'Content-Type' = 'multipart/form-data' ; 'api-key' = "API_KEY"} -Method Post -Body #{"scan_type" = "all"; "file" = "$fileqq" }
powershell command error
It would be helpful for me if someone pointed out the error or correct my converted command
Thank you very much for the help.

Related

MongoDB Atlas interaction with PowerShell

I need help with the connection MongoDB atlas API with PowerShell. With bash, it works perfectly
curl --include --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
--header "Accept: application/json" \
--header "Content-Type: application/json" \
"https://cloud.mongodb.com/api/atlas/v1.0/orgs/{ORG-ID}?pretty=true"
but I'd like to do the same thing Powershell, Can someone help with that? (
#RamanSilopal Thank you so much for the link :)
I've converted it to PowerShell like that:
$ApiPrivateKey
$ApiPublicKey
$Uri = 'https://cloud.mongodb.com/api/atlas/v1.0/groups/{ORG-ID}/accessList?pretty=true'
[securestring]$secStringPassword = ConvertTo-SecureString $ApiPrivateKey -AsPlainText -Force
[pscredential]$credential = New-Object System.Management.Automation.PSCredential ($ApiPublicKey, $secStringPassword)
Invoke-RestMethod -Uri $Uri -ContentType Application/Json -Headers #{Authorization = “Basic $base64AuthInfo”} -Credential $credential -Method Get

How convert curl file upload command to Invoke-RestMethod?

I would like to convert the following command:
$ curl -X POST \
-H 'Content-Type: multipart/form-data' \
-H "Session-Token: [Session Token]" \
-H "App-Token: [MyToken] " \
-F 'uploadManifest={"input": {"name": "Uploaded document", "_filename" : ["file.txt"]}};type=application/json' \
-F 'filename[0]=#file.txt' \
'http://path/to/glpi/apirest.php/Document/'
Using the Invoke-RestMethod command.
I follow arrived at the following result, but impossible to understand how to pass this part to this :
"-F 'uploadManifest={"input": {"name": "Uploaded document", "_filename" : ["file.txt"]}};type=application/json' \"
My result :
$header = #{} ;
$header['Session-Token'] = $session
$header['App-Token'] = $apptoken
$header['Accept'] = "application/json"
$header['Content-Type'] = "multipart/form-data"
$body_input = #{}
$body_input["name"] = "My Document"
$body_input["_filename"] = "MyDoc.txt"
$InputObjectTab = #{} ;
$InputObjectTab."input" = $body_input ;
$JsonItem = ConvertTo-Json $InputObjectTab
$FilePath = "‪C:\Users\MyUser\Downloads\test.txt" ;
$uri = "$GlpiUri/apirest.php/Document"
$GlpiDocument = Invoke-RestMethod -uri $uri -Method Post -Headers $header -ContentType 'image/jpg' -InFile $FilePath
As you understand, this command allows you to upload a file using a REST API
Any ideas ?

cURL command works in git bash but not in cmd and powershell

The folowing command works in git bash but not in cmd and powershell
curl -X POST http://localhost:5678/api/findgen -H 'Content-Type: application/json' -d '{"a": "Val 1","b": "Val 2","c": "Val 3","d": "Val 4"}' -o "file.json"
I get error in cmd such as -
curl: (6) Could not resolve host: application
curl: (6) Could not resolve host: Val 1,b
curl: (6) Could not resolve host: Val 2,c
curl: (6) Could not resolve host: Val 3,d
curl: (3) [globbing] unmatched close brace/bracket in column 6
What can be the issue?
Just read the error message:
Invoke-WebRequest Cannot bind parameter 'Headers'. Cannot convert the "Content-Type:
application/json" value of type "System.String" to type
"System.Collections.IDictionary".
In PowerShell, curl is an alias for the Invoke-WebRequest cmdlet. As the error points it out, the Header parameter must be a IDictionary, not a string. This is how it looks like in PowerShell:
#{"Content-Type"= "application/json"}
Some parameters are also different. This is how I would script the request:
Invoke-WebRequest `
-Uri "http://localhost:5678/api/findgen" `
-Headers #{"Content-Type"= "application/json"} `
-Body '{"a": "Val 1","b": "Val 2","c": "Val 3","d": "Val 4"}' `
-OutFile "file.json" `
-Method Post
So here is the adapted syntax as a one liner :
curl.exe "-X" "POST" "https://reqbin.com/echo/post/json" `
"-H" "Content-Type: application/json" `
"-d" '{\"a\": \"Val 1\",\"b\": \"Val 2\",\"c\": \"Val 3\",\"d\": \"Val 4\"}' `
"-o" "file.json"
And a way a little more friendly for JSON :
curl.exe "-X" "POST" "https://reqbin.com/echo/post/json" `
"-H" "Content-Type: application/json" `
"-d" (#{a='Val 1';b='val 2';c='Val 3';d='Val 4'} | ConvertTo-Json -Compress) `
"-o" "file.json"
I see those "Could not resolve host" only with C:\Windows\System32\curl.exe on Windows 10 (build 17063 or later), because of the way the Windows curl.exe native program interprets single and double quotes.
If you inverse/escape those quotes, it does work (on CMD)
C:\Windows\System32\curl -X POST http://localhost:5678/api/findgen \
-H "Content-Type: application/json" \
^^^
double-quotes
-d "{\"a\": \"Val 1\",\"b\": \"Val 2\",\"c\": \"Val 3\",\"d\": \"Val 4\"}" -o "file.json"
^^^
double quotes outside, escaped double-quotes inside: valid JSON
This is similar to "How do I POST JSON with Curl?"
On Powershell, I had to escape double quotes (backtick, as commented), and escape {}: {{}}
PS D:\> C:\Windows\System32\curl -X POST https://reqbin.com/echo/post/json `
-H "Content-Type: application/json" `
-d "{{`"login`":`"my_login`",`"password`":`"my_password`"}}"
Alternatively:
PS D:\> C:\Windows\System32\curl.exe -X POST https://reqbin.com/echo/post/json `
>> -H "Content-Type: application/json" `
>> -d '{{""login"":""my_login"",""password"":""my_password""}}'
{"success":"true"}
From Steven's post:
PS D:\> C:\Windows\System32\curl.exe -X POST -H "Content-Type: application/json" `
-d '{""north"": ""each south""}' https://reqbin.com/echo/post/json
{"success":"true"}
Using curl.exe alone means using the MingW Git for Windows curl.exe
PS D:\> curl.exe -X POST -H "Content-Type: application/json" `
>> -d '{""north"": ""each south""}' https://reqbin.com/echo/post/json
curl: (6) Could not resolve host: each
curl: (3) unmatched close brace/bracket in URL position 6:
south} https://reqbin.com/echo/post/json
You therefore need to escape curly brackets, and remove any space:
PS D:\> curl.exe -X POST -H "Content-Type: application/json" `
>> -d '{{"north":"each south"}}' https://reqbin.com/echo/post/json
{"success":"true"}
Or, using spaces, with single quotes:
PS D:\> curl.exe -X POST -H "Content-Type: application/json" `
>> -d '{\"north\": \"each south\"}' https://reqbin.com/echo/post/json
{"success":"true"}
On CMD If you want to keep those quotes unchanged, used the mingw curl.exe packaged with Git For Windows, at least on CMD.
C:\path\to\git\mingw64\bin\curl.exe -X POST http://localhost:5678/api/findgen \
-H 'Content-Type: application/json' \
-d '{"a": "Val 1","b": "Val 2","c": "Val 3","d": "Val 4"}' -o "file.json"
^^^
You can keep the quotes as-is
As commented, in a Powershell session, curl itself is an alias for Invoke-WebRequest.
I tested it with:
PS D:\> Get-Alias -Name curl
CommandType Name Version Source
----------- ---- ------- ------
Alias curl -> Invoke-WebRequest
PS D:\> curl -uri https://reqbin.com/echo/post/json `
>> -Method 'POST' -ContentType "application/json" `
>> -Body "{""login"":""my_login"",""password"":""my_password""}"
StatusCode : 200
StatusDescription : OK
Content : {"success":"true"}
RawContent : HTTP/1.1 200 OK
Connection: keep-alive
CF-Cache-Status: DYNAMIC
cf-request-id: 0917a97460000053c82aa69000000001
Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/bea...
Forms : {}
Headers : {[Connection, keep-alive], [CF-Cache-Status, DYNAMIC], [cf-request-id, 0917a97460000053c82aa69000000001], [Expect-CT, max-age=604800,
report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : System.__ComObject
RawContentLength : 19

How to convert curl POST with headers authorization and form to PowerShell v3.0

I have follwoing curl command which I would like to convert to PowerShell (PowerShell v3.0):
curl -s -k -H 'Authorization: api_key 1234567890' -F upload_file=#"C:\path\to\file" -X POST "https://my.url.com/submit"
What I have so far:
$Body= #{ "upload_file" = "C:\path\to\file" };
$Headers = #{ "Authorization" = "api_key 1234567890" };
$Uri = "https://my.url.com/submit"
Invoke-WebRequest -Method Post -Uri $Uri -H $Headers -Body $Body
I think the form parameter is the issue.
Thanks in advance.

Converting Curl API Call to Invoke-WebRequest in PowerShell 5

I have done a bunch of searches, but nothing so far as helped me solve this. Any help is appreciated.
I am trying to convert a curl command to Invoke-WebRequest, but for some reason I am not getting a response back. I have tried:
$headers = #{
outh_a = "WEBREQ";
oauth_key = "key";
etc...
}
Invoke-WebRequest -Uri $url -Method POST -Body "{}" -Headers $headers -Verbose
The curl command looks like this:
.\curl.exe -x POST -d "{}" -H "oauth_a: WEBREQ" -H "oauth_key:key" -H "Content-Type: application/json" -H "oauth_sm:HMAC-SHA2" -H "oauth_t:timestamp"-H "oauth_s:key+signature=" "https://example.com/services/api/request?t=data&a=data2&n=404&i=0"
The command works perfectly and returns the data. I am using PowerShell as we want to parse through the data once received. Any help is greatly appreciated.
The curl command will fail if I submit it without -d "{}", so that part is required. The server I guess is expecting to receive a specific amount of data.
I am not sure what is going on to prevent a response. I have tried curl from the same machine I am doing the PowerShell script on and it works. I even used SoapUI to make the same call and it works there too.
Edit:
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
[System.Net.WebRequest]::DefaultWebProxy.Credentials =
[System.Net.CredentialCache]::DefaultCredentials
[Net.ServicePointManager]::SecurityProtocol =
[Net.SecurityProtocolType]::Ssl3, [Net.SecurityProtocolType]::Tls,
[Net.SecurityProtocolType]::Tls11, [Net.SecurityProtocolType]::Tls12
$Domain = "https://example.com/services/api/request?t=oauth_auth_token&a=appid&n=404&i=0"
# OAUTH Authorization Request Header
$Header = #{
o_nonce = 'TEST'
o_con_key = 'key'
o_sig_meth = 'type'
o_timestamp = 'timestamp'
o_sig = 'signature'
o_ver = '1.0'
o_realm = 'http://example.com/services'
}
$Body = #{}
$API_Response = Invoke-RestMethod -Method POST -Headers $Header -Uri $Domain -Body $Body -Verbose -TimeoutSec 20
Update:
#MikeW I'd have to look at your PS code in more detail, could you post the entire API call minus the sensitive information (api key etc...)?
Also, on a side note, sometimes just passing the parameters on the URI works just as well. Have you tried passing the parameters through the URI? You can see the following example of an API call I'm making using just the URI:
Invoke-RestMethod -Uri ("$EndpointURL/Tickets/$TicketID/?username=$ServiceAccount&apiKey=$APIKey");