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 ?
Related
I am trying to use the Invoke-RestMethod to upload an attachment to a Smartsheet using the API.
This is the curl example from the Smartsheet API Documentation:
curl https://api.smartsheet.com/2.0/sheets/{sheetId}/attachments \
-H "Authorization: Bearer ll352u9jujauoqz4gstvsae05" \
-H "Content-Type: application/msword" \
-H 'Content-Disposition: attachment; filename="ProgressReport.docx"' \
-H "Content-Length: FILE_SIZE" \
-X POST \
--data-binary #ProgressReport.docx
This is my Powershell code.
$BaseURI = "https://api.smartsheet.com/2.0"
$Id = {sheet id} #sheet id passed a parameter
$Uri = "{0}/sheets/{1}/attachments" -f $BaseUri, $id
$mimetype = ""application/vnd.openxmlformats-officedocument.wordprocessingml.document"
$FileName = "MyDocument.docx"
$Config = Read-Config #reads authentication token from text file"
$token = ConvertTo-SecureString -String $config.APIKey -AsPlainText -Force
$response = Invoke-RestMethod -Method POST -Uri $Uri -InFile $FileName -ContentType $mimetype -Authentication:Bearer -token $token
What I get is this response:
{ "errorCode" : 1008, "message" : "Unable to parse request. The following error occurred: Request body must be either a JSON
| object or JSON array.", "refId" : "12y60zzovzndm" }
If I try to post a text file with just the work "test" in it I get this error.
{ "errorCode" : 1008, "message" : "Unable to parse request. The following error occurred: Unrecognized token 'test': was expecting 'null', 'true', 'false' or NaN\n at [Source: REST input; line: 1, column: 6]", "refId" : "lbstw0mq73l9" }
If I do this API call in Postman it works fine.
I know there is a C# SDK but I'm building a PowerShell module and I don't want those .dll files as a requirement for this module.
OK I got this to work thanks to Postman.
I build the headers as a hashtable"
Name Value
---- -----
Content-Type application/vnd.openxmlformats-officedocument.wordprocessingml.document
Authorization Bearer VcjJ....
Content-Disposition attachment; filename="CWilliams.docx"
Convert the input file into a byte array with:
$body = [System.IO.File]::ReadAllBytes($path)
Then issue the statement:
$response = Invoke-RestMethod -Method 'POST' -Uri $Uri -Headers $Headers -Body $body
From what I understand about the Invoke-RestMethod function the -inFile parameter is supposed to handle all this for you but it doesn't work with the Smartsheet API.
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.
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.
How do i convert this curl command to powershell? This works perfectly using curl however in powershell i am geting 401 unauthorized.
I have tried everything i can think of. This code can only be executed inside a certain environment. i am trying to pass a cookie i know is valid into the header of the second. The first request works well, the second request which is meant the return json does not. Instead returns 401
The command requires cookies to authenitcate
curl.exe -vu SuperGabriel:SuperGabriel#2019 -X POST -H "X-Application: 3rdParty" https://webadmin.td90.centile-dev.com/restletrouter/v1/service/Login --insecure
curl.exe -v -H "Cookie: thirdParty_SESSIONID=6483556424564819468" -H "X-
Application: 3rdParty" https://webadmin.td90.centile-dev.com/restletrouter/v1/3rdParty/AdmtiveDomain --insecure
curl.exe -v -H "Cookie: thirdParty_SESSIONID=1312545750448673312" -H "X-Application: 3rdParty" https://webadmin.td90.centile-dev.com/restletrouter/v1/3rdParty/CallRecord/0.106.?day=20190301 -k --insecure -o
"C:\Users\stephenm\Documents\test.csv"
Here is my powershell code so far.
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
$user = "SuperGabriel"
$pass = "SuperGabriel#2019"
$pair = "$($user):$($pass)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"
$headers = #{
"Authorization" = $basicAuthValue
"X-Application" = "3rdParty"
}
$login = Invoke-WebRequest -Uri https://webadmin.td90.centile-dev.com/restletrouter/v1/service/Login -Headers $headers -Method Post
$headers = #{
"Authorization" = $basicAuthValue
"X-Application" = "3rdParty"
"Cookie" ="thirdParty_SESSIONID=4436753218874838616"
"Content-Type" = "application/json"
}
try
{
$admtiveDomains = Invoke-WebRequest -Uri https://webadmin.td90.centile-
dev.com/restletrouter/v1/3rdParty/AdmtiveDomain -Headers $headers -Method
Get
}catch{
echo $ErrorMessage = $_.Exception.Message
}
many thanks
Is it possible you need to get a token first that you then need to convert to a base64 string?
$uri = 'https://webadmin.td90.centile-dev.com/restletrouter/v1/service/Login'
$body = #{ username = 'SuperGabriel'; password = 'SuperGabriel#2019' }
$bodyjson = $body | convertTo-Json
$ctype = "application/json"
$token = invoke-restmethod -uri $uri -method POST -body $bodyjson -contenttype $ctype
I don't know what object $token would return, but you would essentially then convert the returned string and continue on from there.
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($token))
I have a requirement to convert a working curl command to Invoke-WebRequest command
The command is used to create a project in SonarQube
Curl:
curl -u as123123112312: -X POST "http://sonarqube.it.company.net:9000/api/projects/create?key=%project_key%&name=%project_name%" > NUL
the command I tried:
$e = #{
Uri = "http://sonarqube.it.company.net:9000/api/projects/create?key=%project_key%&name=%project_name%"
Headers = #{"Authorization" = "Token as123123112312"}
}
Invoke-WebRequest #e -Method POST
Error:
Invoke-WebRequest : The remote server returned an error: (401) Unauthorized
Does anyone have an idea of converting curl to invoke-webrequest
This has been asked before. When you are posting, you need to have a body to send too, example:
$username = "as123123112312";
$password = "blah";
$Bytes = [System.Text.Encoding]::UTF8.GetBytes("$username`:$password");
$encodedCredentials = [System.Convert]::ToBase64String($bytes);
$body = "your content (i.e. json here)";
Invoke-WebRequest -Method Post -Body $body -Headers #{ "Authorization" = "Basic " + $encodedCredentials} -Uri "http://sonarqube.it.company.net:9000/api/projects/create?key=%project_key%&name=%project_name%"