2

I have a Python script that posts a local file to a given URL using requests:

import requests
url = 'https://www.myWebsite.com/ext/ext/ext'
data = "/Users/ME/Documents/folder/folder/folder/test.json"
with open(data) as test:
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    r = requests.post(url, data=test, headers=headers)

I want to do the exact same thing in PowerShell.

I've read this post on User powershell script to post to URL?, but it seems very verbose/involved. Is there any short, easy way to do this? Is there such a thing as a 'requests' equivalent for PowerShell?

KyleMit
  • 30,350
  • 66
  • 462
  • 664
user3749214
  • 144
  • 3
  • 8
  • You saw this answer? http://stackoverflow.com/questions/17325293/invoke-webrequest-post-with-parameters – Victor Jun 20 '14 at 16:20
  • That half-works. I found the solution: `$file = Get-Content test.json` -> `Invoke-WebRequest -Uri https://www.myWebsite.com/ext/ext/ext -Method POST -Body $file` – user3749214 Jun 20 '14 at 16:40

1 Answers1

2

You want to use Invoke-WebRequest (get raw request data) or Invoke-RestMethod (parses JSON, XML, etc. turns into a PowerShell obj).

For your use case, it would look something like this with Invoke-WebRequest:

$uri = 'https://www.myWebsite.com/ext/ext/ext'
$data = Get-Content "test.json"
$result = Invoke-WebRequest -Uri $uri -Body $data -ContentType 'application/json' -Method POST
$result.RawContent
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Casey
  • 21
  • 1