invoke-webrequest gives different object for header property in PS 5.1 vs PS CORE 7.1

Viewed 214

I'm getting mixed output between same piece of running code on PS 5.1 and PS Core 7.1

PS 5.1

get-host


Name             : Windows PowerShell ISE Host
Version          : 5.1.17763.2268

$response = Invoke-WebRequest google.com
$response.headers

Key               Value                                                                                         
---               -----                                                                                         
X-XSS-Protection  0                                                                                             
X-Frame-Options   SAMEORIGIN                                                                                    
Vary              Accept-Encoding                                                                               
Transfer-Encoding chunked                                                                                       
Accept-Ranges     none                                                                                          
Cache-Control     private, max-age=0       

Name             : ConsoleHost
Version          : 7.1.3

$response = Invoke-WebRequest google.com
PS C:\> $response.headers

Key               Value
---               -----
Date              {Tue, 14 Dec 2021 15:41:47 GMT}
Cache-Control     {max-age=0, private}
P3P               {CP="This is not a P3P policy! See g.co/p3phelp for more info."}
Server            {gws}

I tried the usebasicparsing on the 5.1 instance, same result as above. Why am I getting this strange object from the powershell core commandlet? I have to convert the properties to string to get them to work equally well on PS core.

Am I doing something wrong?

thanks, ionut

1 Answers

You are doing nothing wrong.

If you look at the Invoke-WebRequest documentation you will see that they return either a BasicHtmlWebResponseObject (powershell core) or a HtmlWebResponseObject (windows powershell).

In both cases the header is a WebResponseObject.Headers object, which is a Dictionary<String,IEnumerable<String>>

My guess is that Windows Powershell is converting the IEnumerable<String> to a string before returning it, while Powershell Core is keeping the underlying .NET type.

In your case you can convert the headers in every case to strings with e.g.:

$response.Headers.GetEnumerator() | ForEach-Object { $_.Value -join "," }

Windows Powershell and Powershell Core are similar enough, but not 100% compatible, so you will always find cases like this where you have differences that you have to take care of if you want to support both versions.

Related