从 Powershell Core/7 通过密钥访问 .Net KeyValuePairs
从 Powershell (core/7) 中的 .Net 类访问 KeyValuePairs 的最佳方法是什么? 我发现我尝试使用的类不允许我使用索引器中的键名称访问该值。
我目前的理论是,这是由于底层 .net 类使用了 Powershell 无法解析的扩展方法(但我可能走错了路......)。
下面是一个示例对象:
$HTTPMsg = [System.Net.Http.HttpRequestMessage]::new()
$HTTPMsg.Headers.Add("WWW-Authenticate", "Basic realm=C:\xxx")
$HTTPMsg.Headers.Add("Date", "Wed, 02 Mar 2022 09:41:36 GMT")
$HTTPMsg.Headers
***Output:
Key Value
--- -----
WWW-Authenticate {Basic realm=C:\xxx}
Date {Wed, 02 Mar 2022 09:41:36 GMT}
理想情况下,我希望能够通过以下方式访问日期值:
$MyDate = $HTTPMsg.Headers["Date"]
但这会返回 $null。
到目前为止,我发现的最好的方法如下,但这看起来比应有的要困难得多:
$MyDate = $HTTPMsg.Headers.Value[$HTTPMsg.Headers.Key.IndexOf("Date")]
我错过了什么?
提前致谢!
What is the best way to access KeyValuePairs from .Net classes in Powershell (core/7)?
I have found that the classes I'm trying to use will not let me access the value using the key name in the indexer.
My current theory is that its due to the underlying .net classes making use of Extension methods which Powershell cannot resolve (but I could be on the wrong path with that...).
Here is an example object:
$HTTPMsg = [System.Net.Http.HttpRequestMessage]::new()
$HTTPMsg.Headers.Add("WWW-Authenticate", "Basic realm=C:\xxx")
$HTTPMsg.Headers.Add("Date", "Wed, 02 Mar 2022 09:41:36 GMT")
$HTTPMsg.Headers
***Output:
Key Value
--- -----
WWW-Authenticate {Basic realm=C:\xxx}
Date {Wed, 02 Mar 2022 09:41:36 GMT}
Ideally, I would have liked to be able to access the Date value with:
$MyDate = $HTTPMsg.Headers["Date"]
But this returns $null.
So far the best way I've found is as follows, but this looks way harder than it should be:
$MyDate = $HTTPMsg.Headers.Value[$HTTPMsg.Headers.Key.IndexOf("Date")]
What am I missing?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试一下。
输出:
Give this a try.
Output:
@Jeroen Mostert 在评论中回答:
$HTTPMsg.Headers.GetValues("Date")
@Jeroen Mostert answered in the comments:
$HTTPMsg.Headers.GetValues("Date")