Abbas.Kh
Abbas.Kh

Reputation: 37

How to Pass JSON Parameter with POST method on powershell 2.0?

I have a Powershell code that is work very fine in powershell version 3.

I need to run this code in powershell 2.0 too. But Invoke-WebRequest not supported in PS version 2.0.

Please help me!

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

Upvotes: 0

Views: 614

Answers (1)

Theo
Theo

Reputation: 61028

Untested, but I think this may help:

$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

Upvotes: 1

Related Questions