Powershell Invoke-RestMethod Error when passing xml body
<p>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:</p>

<blockquote>
  <p>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</p>
</blockquote>

<p>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.</p>

<pre><code>#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 = @"
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;rs:model-request xmlns:rs="http://www.ca.com/spectrum/restful/schema/request" throttlesize="250000"&gt;
&lt;rs:target-models&gt;&lt;rs:models-search&gt;&lt;rs:search-criteria xmlns="http://www.ca.com/spectrum/restful/schema/filter"&gt;
&lt;devices-only-search /&gt;
&lt;filtered-models&gt;
&lt;has-substring-ignore-case&gt;
&lt;attribute id="0x1006e"&gt;
&lt;value&gt;SERVER1234&lt;/value&gt;
&lt;/attribute&gt;
&lt;/has-substring-ignore-case&gt;
&lt;/filtered-models&gt;
&lt;/rs:search-criteria&gt;
&lt;/rs:models-search&gt;
&lt;/rs:target-models&gt;
&lt;/rs:model-request&gt;
"@

$searchResults = Invoke-RestMethod -Method Post -Uri $searchURI -Credential $cred -Body $searchBody -ContentType "application/xml"
write-host $searchResults.OuterXml
</code></pre>