Vineeth Chandran
Vineeth Chandran

Reputation: 51

Rest call with PUT method in powershell version 2 (.Net) with content body

Here is my REST call (PUT) with powershell version 2 (using .net class System.Net.HttpWebRequest)

The call has a body which is an XML file and i can make this work in powershell version 3 and above using invoke-WebRequest with the property "Body". But i have to do this with .net class as we have some powershell version 2 systems.

Below is my code

 $psuri = "$restUri"
[string]$psdata = Get-Content -path "$myfile.xml"
[System.Net.HttpWebRequest]$global:ps = [System.Net.HttpWebRequest] [System.Net.WebRequest]::Create("$psuri");

$psbuffer = [System.Text.Encoding]::UTF8.GetBytes($psdata)
$ps.ContentLength = $psdata.length
$ps.ContentType = "application/xml"
    [System.IO.Stream]$outputStream = [System.IO.Stream]$ps.GetRequestStream()
    $outputStream.Write($psdata, 0, $psbuffer.Length)




$ps.method = "PUT"
$ps.Accept = "application/xml"
$ps.AllowAutoRedirect = $false
$ps.KeepAlive = $true
$ps.CookieContainer = $CookieContainer
$ps.PreAuthenticate = $true

        #Try
        #{

            [System.Net.HttpWebResponse]$psresponse = $ps.GetResponse() 

The same fails with the error Exception calling "GetRequestStream" with "0" argument(s): "Cannot send a content-body with this verb-type."At line:8 char:9

Upvotes: 0

Views: 709

Answers (1)

Vineeth Chandran
Vineeth Chandran

Reputation: 51

Okay so i finally figured out this one as well. The problem was that the REST was looking for XML data to be PUT and the way i was converting it was not proper. This is what i had to do to get the content (as Raw data)

$psdata = Get-Content -path "$myfile.xml" -Raw

Upvotes: 1

Related Questions