首页 > 解决方案 > 如何在 powershell 2.0 上使用 POST 方法传递 JSON 参数?

问题描述

我有一个在 powershell 版本 3 中运行良好的 Powershell 代码。

我也需要在 powershell 2.0 中运行此代码。但是 PS 2.0 版不支持 Invoke-WebRequest。

请帮我!

$params = "metrics[]=failed:count"
$failed = (Invoke-WebRequest -Uri http://localhost:9000/stats -Method POST -Body $params -ContentType "application/json").Content
$x = $failed | ConvertFrom-Json

标签: powershell

解决方案


未经测试,但我认为这可能会有所帮助:

$params = "metrics[]=failed:count"

$result = @{}
try{
    $request = [System.Net.WebRequest]::Create('http://localhost:9000/stats')
    $request.Method = 'POST'
    $request.ContentType = 'application/json'
    $request.Accept = "application/json"

    $body = [byte[]][char[]]$params
    $upload = $request.GetRequestStream()
    $upload.Write($body, 0, $body.Length)
    $upload.Flush()
    $upload.Close()

    $response = $request.GetResponse()
    $stream = $response.GetResponseStream()
    $streamReader = [System.IO.StreamReader]($stream)

    $result['StatusCode']        = $response.StatusCode
    $result['StatusDescription'] = $response.StatusDescription
    $result['Content']           = $streamReader.ReadToEnd()

    $streamReader.Close()
    $response.Close()
}
catch{
    throw
}

# I suggest checking $result.StatusCode here first..
$x = $result.Content | ConvertFrom-Json

推荐阅读