I'm trying to write a Powershell script that calls a rest web service. The code below is the most basic call I have to make to query the api and return information for a specific device. Running this same script I get inconsistent results where sometimes it works fine and sometimes it returns this error:
Invoke-RestMethod : You must write ContentLength bytes to the request stream before calling [Begin]GetResponse. At E:\temp\temp.ps1:28 char:18 + $searchResults = Invoke-RestMethod -Method Post -Uri $searchURI -Credential $cr ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Invoke-RestMethod], ProtocolViolationException + FullyQualifiedErrorId : System.Net.ProtocolViolationException,Microsoft.PowerShell.Commands.InvokeRestMethodComm and
I cannot figure out what that error means or why it works intermittently. When the Powershell script fails with that error I have run tests against the target web service from Postman and confirmed that the web service is up and functioning normally.
#Get PS Credential Object
$user = "user"
$pass = "password"
$secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($user, $secpasswd)
$searchURI = "http://internal.server.com:8080/spectrum/restful/models"
$searchBody = @"
<?xml version="1.0" encoding="UTF-8"?>
<rs:model-request xmlns:rs="http://www.ca.com/spectrum/restful/schema/request" throttlesize="250000">
<rs:target-models><rs:models-search><rs:search-criteria xmlns="http://www.ca.com/spectrum/restful/schema/filter">
<devices-only-search />
<filtered-models>
<has-substring-ignore-case>
<attribute id="0x1006e">
<value>SERVER1234</value>
</attribute>
</has-substring-ignore-case>
</filtered-models>
</rs:search-criteria>
</rs:models-search>
</rs:target-models>
</rs:model-request>
"@
$searchResults = Invoke-RestMethod -Method Post -Uri $searchURI -Credential $cred -Body $searchBody -ContentType "application/xml"
write-host $searchResults.OuterXml