1

I have the following PowerShell script:

$CURLEXE = 'C:\Windows\System32\curl.exe'
$URL1 = "Example.com"

$GetTokenCurl = '-s', '-v', '-X', 'POST',
    $URL1,
    '-H', 'Content-Type: application/x-www-form-urlencoded',
    '-d', 'grant_type=client_credentials&client_id=12345678&client_secret=abcdefgh',
    '--retry', '2', 
    '--retry-connrefused',
    '--retry-delay', '3'

Write-Host "Command took" (Measure-Command {$GetTokenResponse = & $CURLEXE @GetTokenCurl}).TotalSeconds "Seconds"

$GetTokenJSON = ConvertFrom-Json -InputObject $GetTokenResponse -ErrorAction SilentlyContinue

$SessionToken = $GetTokenJSON.access_token
$AuthBearer = "Authorization: Bearer " + $SessionToken

It gets my Access Token from the SSO server and stores it into the $AuthBearer variable so I can reuse it for later scripts.

My response looks something like this:

{"access_token":"987654321","token_type":"Bearer","expires_in":3600}

I am trying to also validate the HTTP response code from the server, which I have only been able to do (so far) by enabling -v (verbose) output. I am specifically looking for the HTTP response code after < HTTP/1.1 (i.e. 200). I can see this in the Verbose output:

< HTTP/1.1 200 OK

I can't for the life of me find a way to store the JSON response in a variable and check the contents of the Verbose output.

I've tried and failed to write the Verbose output to a text file. I've tried the following two switches, but these mess up my JSON response:

-i, --include       Include protocol response headers in the output
-I, --head          Show document info only

I also tried the --output to a file, but that just wrote my JSON response and not the Verbose response to a file:

--output <file> Write to file instead of stdout

Is it possible using PowerShell and cURL to get the JSON response and check for the HTTP response code?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Simon
  • 97
  • 7
  • `curl` writes the regular output to STDOUT and the verbose (status) output to STDERR. You can separate these 2 streams as described in the answers to the linked question. Personally, I'd recommend going with the one provided by Aaron Schultz. – Ansgar Wiechers Dec 09 '18 at 13:21
  • 1
    "Is it possible using PowerShell and cURL to get the JSON response and check for the HTTP response code?" Yes. I found this to work `curl -X GET "..." -w "status:%{http_code}"` will give both the response and the status code. To suppress the response do "-o null" see: --write-out option for curl for more info. – James Close Feb 25 '19 at 12:28

0 Answers0