PowerShell 7中如何获取名称含连字符的属性值?
在PowerShell 7中获取名称含连字符的属性值
在PowerShell 5中,可通过$variable.'property-name'格式访问名称包含连字符的属性值,但该写法在PowerShell 7中失效。
例如,执行$response.Headers可看到包含Set-Cookie等带连字符的键值对:
$response.Headers Key Value --- ----- Connection keep-alive Request-Context appId=cid-v1:e7e5e5c5-14a3-41a0-8724-6a5090e83fe5 Strict-Transport-Security max-age=15724800; includeSubDomains Content-Length 0 Date Fri, 07 Jun 2024 14:37:22 GMT Location https://auth.barracudanetworks.com/oauth2/authorize?client_id=j1Skduh5hOyyW7OqlPe8qSKwLukh... Set-Cookie .AspNetCore.Correlation.YzsM7RBu_2pvg6AJyrCDQ4gwSglsRPz6rIi9EL1Siu0=N; expires=Fri, 07 Jun...
在PowerShell 5中,$response.Headers.'Set-Cookie'可正常返回对应值,但PowerShell 7中执行该命令返回空值。
解决办法
使用索引器直接访问
对于字典/集合类型的对象,直接通过键名的索引器访问是最可靠的方式,PowerShell 7中完全支持:$response.Headers['Set-Cookie']调用类型原生方法获取值
如果$response.Headers是System.Net.Http.Headers.HttpResponseHeaders类型(常见于.NET Core/.NET 5+的HTTP响应),可以调用其GetValues方法获取对应头的值(该方法会返回数组,因为HTTP头可能存在多个值):$response.Headers.GetValues('Set-Cookie') # 若需转为单个字符串,可使用 -join 处理 $response.Headers.GetValues('Set-Cookie') -join ';'确认对象类型后适配访问方式
先通过命令查看对象的具体类型,再根据类型文档选择对应的访问方式:# 查看对象类型 $response.Headers.GetType().FullName比如如果是
WebHeaderCollection,除了索引器,也可以用Get方法:$response.Headers.Get('Set-Cookie')
内容的提问来源于stack exchange,提问作者Roger McCarrick
相关产品推荐
相关产品推荐

