我有一个用于 url 获取查询的 powershell 脚本。我使用外部curl.exe,因为Invoke-Webrequest和.NET无法使用GET和body进行查询。
我只需要http响应代码。
$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
这是我需要在变量中捕获 http 代码的输出,但它仅显示在 powershell 控制台中。但输出变量仅包含底部的行“Response: XYZ”,因此我只能访问卷曲结果。有什么办法吗
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
输出:
Response: {"records":[{"value":{"TEST":"1","TEST2":"2"}}]}
对您问题的general答案是将redirection
2>&1
附加到您的curl.exe
调用中,导致PowerShell也捕获stderr输出(这是curl.exe
打印其进度和详细信息的地方,以及错误消息)。
特定解决方案,假设您只对HTTP状态代码感兴趣:
$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
) 静音进度和错误输出。
-w '%{http_code}'
收到响应正文后输出 HTTP 状态代码。
-o /dev/null
丢弃响应正文,因此实际上仅打印 HTTP 状态代码。
/dev/null
实际上并不是Windows上的空设备,而是被视为导致错误的文字路径;然而,这个错误可以被忽略,并且由于
-s
,实际上 is被忽略;一个正确的、但仅限于 Windows 的解决方案是针对
NUL
(在类 Unix 平台上,您将在当前目录中创建一个名为 NUL
的输出文件)。