Search code examples
powershellhttpwebrequestpowershell-3.0webrequest

Powershell Invoke-WebRequest casting issue on PS3 not PS4


I run the following command in my PS script:

$apiResult = Invoke-WebRequest -Uri $myURL -Body $body -DisableKeepAlive -Headers $headers -Method Post -TimeoutSec 120 -ContentType $contentType -UseBasicParsing

This fails on the following error:

Unable to cast object of type \u0027System.Management.Automation.PSObject\u0027 to type \u0027System.String\u0027

Here is the catch:

  • The types of the supplied variables are System.String (for $body, $myURL, $contentType) and System.Collection.Hashtable (for $headers)
  • This fails without calling the actual service behind the URL (verified in service logs)
  • Running this script with the same parameters on the machine with Powershell version 4 does not create this error and actually returns expected result

I believe this is a bug but i have not been able to find any mention of it on google or any other areas including documentation.


Solution

  • Well...After long time digging I found that the issue was one of the values in my headers hashtable was not a string! not sure why this passes on powershell 4...maybe the casting there is more flexable than in PS3