I am trying to process a multipart GET call in powershell and then save the zipfile it contains to disk. I can execute this:
$response = Invoke-RestMethod -Uri $reqUrl -Method Get -Headers $headers
and then echo out the filename and contents. In order to save the file, I tried this:
$response = Invoke-RestMethod -Uri $reqUrl -Method Get -Headers $headers -ContentType "multipart/form-data" -Outfile result.zip
This raises an error (Invalid Operation). So I tried this:
$response = Invoke-RestMethod -Uri $reqUrl -Method Get -Headers $headers -ContentType "application/zip" -Outfile result.zip
This creates a file called result.zip which isn't valid. I know that the response is multipart, so while this doesn't raise an error, I am not surprised that the file is invalid because it must contain all of the parts.
I have looked around, but all I find are ways of using Invoke-RestMethod to POST mulitpart content.
This is the error when I try to open the resulting zip file:
I have also tried to decode the result as below, but with the same results.
$B64String = $response.resultObject
Write-Host "resultObject size: $([Math]::Round($B64String.Length / 1Mb,2)) MiB"
$swDecode = [System.Diagnostics.Stopwatch]::StartNew()
$bytes = [System.Convert]::FromBase64String($B64String)
$swDecode.Stop()
Write-Host "Decoded size: $([Math]::Round($bytes.Count / 1Mb,2)) MiB"
Write-Output $bytes > $($response.fileName)
I found the answer
$response = Invoke-RestMethod -Uri $reqUrl -Method Get -Headers $headers
$response | ConvertTo-Json
[IO.File]::WriteAllBytes($response.fileName, [System.Convert]::FromBase64String($response.resultObject))
Related
Can you please help me, How can I upload a Json file in the body of PUT request, is the following approach correct?
'''
$filename = "C:/Users/timtim/Downloads/default.json"
[hashtable]$headers=#{
'Authorization' = "Bearer $token"
}
$url= "url.com"
$statusCode = Invoke-WebRequest -Uri $url -Method PUT -InFile $filename -Headers $headers -ContentType "application/json"
Write-Host "$statusCode"
'''
Try this:
$filename = "C:/Users/timtim/Downloads/default.json"
$content = gc $filename
[hashtable]$headers=#{}
$headers.Add("Authorization", "Bearer $token")
$headers.Add('Content-Type', 'application/json')
$statusCode = Invoke-WebRequest -Uri $url -Method PUT -Body $content -Headers $headers
Write-Host $statusCode
Your syntax in the $headers was off. I replaced that part by initializing the hashtable, then we add our pieces to that one at a time. I was not sure why URL was in there so I removed it. You can add that back if needed. Send your JSON in a -body param. There is also $content = gc $filename where gc is an alias for "get-content". It's getting the content of the JSON from the file with that.
I have a web server that responds to a request https://localhost/GetUpdateInfo with a body [{"ipAddress": "10.200.2.55"}]
In postman its Work but in powershell i can`t do this because body begins from array.
When i do exmple code:
$Url = "https://localhost/GetUpdateInfo"
$Body = #(#{
ipAddress = "10.200.2.55"
})
$jsonBody = ConvertTo-Json -InputObject $Body
Invoke-RestMethod -Method 'Post' -Uri $url -Body $jsonBody
i hve error: Invoke-RestMethod : Block length does not match with its complement.
The content type of all POST requests is application/x-www-form-urlencoded unless specified.
Add -ContentType application/json to your last line call so your json is sent correctly.
Invoke-RestMethod -Method 'Post' -Uri $url -Body $jsonBody -ContentType 'application/json'
$header = #{'Authorization'='Basic <auth code value>'}
$ping = Invoke-RestMethod -Uri "https://api.docparser.com/v1/ping" -Headers $header
ping works fine...returns "pong". I then make a request for the Parser ID which is needed for uploading documents. I am able to retrieve this value successfully.
$parser = Invoke-RestMethod -Uri "https://api.docparser.com/v1/parsers" -Headers $header
$parserID = $parser.id
Now here is where I try to upload a pdf, which fails.
$fileToParse = "C:\test.pdf"
$body = #{'file'=$fileToParse}
$uploadDoc = Invoke-RestMethod -Uri "https://api.docparser.com/v1/document/upload/$parserID" -Method Post -Headers $header -ContentType 'multipart/form-data' -Body $body
API response keeps saying "Error: input empty"
This is the documentation from Docparser on how to upload pdfs:
Any thoughts on what I'm doing wrong here? Thanks in advance,
Eric
The problem is that your body currently just contains the path to your local file. Docparser expects however the content of the file as multipart/form-data.
I never worked with PowerShell, but I think something like this should work for you:
$body = #{
"file" = Get-Content($fileToParse) -Raw
}
I got the code from this answer: How to send multipart/form-data with PowerShell Invoke-RestMethod
I have a very basic requirement to call a RESTful API. I am currently on a Windows 2012 R2 server using version 4 of PowerShell.
Here is my code:
$logon = #{
username = 'blah'
password='blah'
}
$body = $logon | ConvertTo-Json
$URI = 'https://URL/Logon'
Invoke-WebRequest -URI $URI -Method POST -Body $body -ContentType 'application/json' -Verbose
I get the following result:
{"LogonResult":"blahblahblah"}
How do I extract just the logon token to reuse as a variable? I've already put a variable at the beginning of the command:
$token = (Invoke-WebRequest -URI $URI -Method POST -Body $body -ContentType 'application/json' -Verbose).content
This returns the entire result, not just the token. How do I get just the token as a result?
You can get the value of the returned LogonResult property as follows:
$token = ((Invoke-WebRequest -URI $URI -Method POST -Body $body -ContentType 'application/json' -Verbose).content | ConvertFrom-JSON).LogonResult
Or you simplify this by using Invoke-RestMethod as this returns just the content and converts it to a PSObject automatically:
$token = (Invoke-RestMethod -URI $URI -Method POST -Body $body -ContentType 'application/json' -Verbose).LogonResult
The following works fine on my machine which does not use a web proxy.
return Invoke-RestMethod
-Uri $server$url
-ContentType $contentType
-Headers $headers
-Method $method
-UseDefaultCredentials
Note: the $server$url is an https address, something like https://somewhere.example.com/api/data
Now I'm trying to get it to work in a corporate environment but I am getting a 401 error.
I think this is because there is a corporate proxy which is defined with a proxy.pac file. I have confirmed I can get to the $server$url URI from Internet Explorer. What do I need to do to get the Invoke-RestMethod command to work using the same settings?
I have tried adding the -proxy parameter
$proxy = [System.Net.WebRequest]::GetSystemWebProxy()
$proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials
return Invoke-RestMethod
-Uri $server$url
-ContentType $contentType
-Headers $headers
-Method $method
-UseDefaultCredentials
-Proxy $proxy
-ProxyUseDefaultCredentials
but the -Proxy parameter is expecting a URI not an IWebProxy object.
The accepted answer got me started. Here's the full version
$headers = #{"X-My-ApiKey"=$apiKey}
$contentType = "application/json"
$proxyUri = [Uri]$null
$proxy = [System.Net.WebRequest]::GetSystemWebProxy()
if ($proxy)
{
$proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials
$proxyUri = $proxy.GetProxy("$server$url")
}
if ("$proxyUri" -ne "$server$url")
{
Write-Host "Using proxy: $proxyUri"
return Invoke-RestMethod -Uri $server$url -ContentType $contentType -Headers $headers -Method $method -UseDefaultCredentials -Proxy $proxyUri -ProxyUseDefaultCredentials
}
else
{
return Invoke-RestMethod -Uri $server$url -ContentType $contentType -Headers $headers -Method $method -UseDefaultCredentials
}
Edit: Once incorrect address is provided the command no longer works and returns the address provided instead of the proxy address..
Do not use this:
Using the code snippet in this, I am able to retrieve the proxy uri from PowerShell as such:
[System.Net.WebRequest]::DefaultWebProxy.GetProxy([uri]("http://www.google.com"))
Use this instead:
[System.Net.WebRequest]::GetSystemWebProxy().GetProxy("http://www.google.com")
It still returns the provided URI (or throws) when the uri is invalid, but once correct uri is provided is starts working again.