Powershell console output to variable

34 Views Asked by At

I got a powershell script for a url get query. I use the external curl.exe because Invoke-Webrequest and the .NET is not able to query with GET and with a body.

I just need the http response code.

$header = "Bearer ABCDE"
$ContentType = "application/json"
$url = "http://test/api"

$bodyJson='{""SSELECT1"": ""0"", ""SSELECT2"": ""TEST1""}'
$pattern = "(?<=HTTP/1.1 )\d+"

$output =  & "C:\curl\bin\curl.exe" -X GET -H "Authorization: $header" -H "Content-Type: $ContentType" -d $bodyJson -v $url

Write-Host "Response: " $output

$httpCode = [regex]::Match($output, $pattern).Groups[1].Value

Write-Host "HTTP CODE: " $httpCode

This is the output I need in a Variable to catch the http code, but its only shown in the powershell console. But the output variable conains just the line at the bottom "Response: XYZ", so I have just access to the curl result. Is there any way?

curl.exe :   % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
    In Zeile:9 Zeichen:15
    + ... usgabe =  $(&"C:\curl\bin\curl.exe" -X GET -H "Authorization: $header ...
    +                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (  % Total    % ...  Time  Current:String) [], RemoteException
        + FullyQualifiedErrorId : NativeCommandError
     
                                     Dload  Upload   Total   Spent    Left  Speed
      0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0* Host XY was resolved.
    * IPv6: (none)
    * IPv4: 123
    *   Trying 123...
    * Connected to celle (123) port xy
    > GET test/api HTTP/1.1
    > Host: 123
    > User-Agent: curl/8.6.0
    > Accept: */*
    > Authorization: Bearer ABCDE
    > Content-Type: application/json
    > Content-Length: 57
    > 
    } [57 bytes data]
    < HTTP/1.1 200 OK
    < Connection: keep-alive
    < Content-Type: application/json
    < Content-Length: 278
    < Date: Thu, 14 Mar 2024 12:15:58 GMT
    < 
    { [278 bytes data]
    100   335  100   278  100    57   2989    613 --:--:-- --:--:-- --:--:--  3764
    * Connection #0 to host XY left intact
    


    

Output:

Response:  {"records":[{"value":{"TEST":"1","TEST2":"2"}}]}
2

There are 2 best solutions below

0
mklement0 On BEST ANSWER
  • The general answer to your question is to append redirection 2>&1 to your curl.exe call, causing PowerShell to capture stderr output too (which is where curl.exe prints its progress and verbose information to, alongside error messages).

    • If you later need to separate stdout lines from stderr lines in the combined output, use the technique shown in the bottom section of this answer.
  • The specific solution, for curl, given that you're interested in only the HTTP status code:

$output = 
  C:\curl\bin\curl.exe -s -w '%{http_code}' -X GET -H "Authorization: $header" -H "Content-Type: $ContentType" -d $bodyJson $url -o /dev/null
  • -s (--silent) silences progress and error output.

  • -w '%{http_code}' outputs the HTTP status code on an extra line, after the response body.

  • -o /dev/null discards the response body, so that in effect only the HTTP status code prints.

    • Remove this argument if you want to capture the response body too.

      • You can then separate the response body from the status code as follows:

         $responseBody, $statusCode = 
           ($output | select -SkipLast 1), $output[-1]
        
    • Note that /dev/null isn't actually the null device on Windows and is treated like a literal path that causes an error; however, this error can be ignored and effectively is ignored, due to -s; a proper, but Windows-only solution would be to target NUL (on Unix-like platforms you'd create an output file literally named NUL in the current directory).

1
JamesN On

The return object from Invoke-WebRequest should have the status code as a property and can also take the body data as an argument.

$response = Invoke-WebRequest -Uri $url -Headers $header -Body $body -ContentType application/json

$statusCode = $response.StatusCode