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"}}]}
The general answer to your question is to append redirection
2>&1to yourcurl.execall, causing PowerShell to capture stderr output too (which is wherecurl.exeprints its progress and verbose information to, alongside error messages).The specific solution, for
curl, given that you're interested in only the HTTP status code:-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/nulldiscards 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:
Note that
/dev/nullisn'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 targetNUL(on Unix-like platforms you'd create an output file literally namedNULin the current directory).