0

I'm trying to call Invoke-RestMethod (and running into another unrelated problem) and keep getting errors when trying to pass it the result of a sub-command. Consider:

Invoke-RestMethod -Header @{"Iso-Date"=(Get-Date -Format "r")}

I expect this to run Get-Date -Format "r", assign its output string (the ISO-format date) to the hashtable value for Iso-Date, then use that hashtable as the "Header" argument for the commandlet.

What actually happens is I get an error message

Unable to cast object of type 'System.Management.Automation.PSObject' to type 'System.String'.

This still happens if I assign it to a variable:

$date = (Get-Date -Format "r")
$date.GetType() # -- outputs "String"
Invoke-RestMethod -Header @{"Iso-Date"=$date) # -- Same error message.

If I set $date to a fixed string value, I don't get the error anymore:

$date = "Fri, 20 Mar 2015 16:00:00 GMT"
$date.GetType() # -- outputs "String" as well (!!!)
Invoke-RestMethod -Header @{"Iso-Date"=$date) # -- works fine

What am I doing wrong?

Community
  • 1
  • 1
Coderer
  • 25,844
  • 28
  • 99
  • 154
  • A few additional minutes with Google lead me to try, out of sheer desperation, `$date = (Get-Date -Format "r").ToString()`. This works, but I still have no idea why and would like to know a) where I went wrong and b) how to tell when I can expect to need ToString() in the future – Coderer Mar 20 '15 at 15:31
  • Interesting. `(get-date -format "r") -is [PSObject]` returns `True`, but `("{0:r}" -f (get-date)) -is [PSObject]` returns `False`. – Bill_Stewart Mar 20 '15 at 16:23
  • I believe it may be due to version of .Net/Powershell that is installed. I do not get any errors when I try `Invoke-RestMethod -Header @{"Iso-Date"=(Get-Date -Format "r")}`. Running .Net 4.5.1 and Powershell 5.0 here. Bill_Stewart's `PSObject` tests still hold true with my setup, but the hashtable value assignment is successful. – Booga Roo Mar 20 '15 at 21:00

0 Answers0