【问题标题】:invoke-webrequest gives different object for header property in PS 5.1 vs PS CORE 7.1invoke-webrequest 为 PS 5.1 和 PS CORE 7.1 中的标头属性提供了不同的对象
【发布时间】:2021-12-14 15:54:28
【问题描述】:

我在 PS 5.1 和 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}

我在 5.1 实例上尝试了 usebasicparsing,结果与上面相同。 为什么我从 powershell 核心命令行开关中得到这个奇怪的对象? 我必须将属性转换为字符串才能使它们在 PS 核心上同样有效。

我做错了吗?

谢谢, 离子核

【问题讨论】:

    标签: powershell powershell-core invoke-webrequest


    【解决方案1】:

    你没有做错任何事。

    如果您查看Invoke-WebRequest 文档,您会发现它们返回BasicHtmlWebResponseObject (powershell core)HtmlWebResponseObject (windows powershell)

    在这两种情况下,标头都是WebResponseObject.Headers 对象,即Dictionary<String,IEnumerable<String>>

    我的猜测是 Windows Powershell 在返回之前将 IEnumerable<String> 转换为字符串,而 Powershell Core 保留了底层的 .NET 类型。

    在您的情况下,您可以将每种情况下的标题转换为字符串,例如:

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

    Windows Powershell 和 Powershell Core 非常相似,但不是 100% 兼容,因此您总是会发现这样的情况,如果您想同时支持这两个版本,则必须注意这些差异。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-23
      • 1970-01-01
      相关资源
      最近更新 更多