如何提取PowerShell中Select-String生成数组的request属性值
提取MatchInfo对象中的request属性值
方法1:解析Line属性为哈希表取值
Select-String返回的MatchInfo对象,其Line属性存储了匹配到的字符串内容(即你看到的@{number=xxx; request=xxx}格式)。我们可以将这个字符串转换为哈希表,再直接提取request值:
$requestValues = $2 | ForEach-Object { # 移除首尾的@{和},再将字符串转换为哈希表 $hashContent = $_.Line -replace '^@{|}$', '' $hash = $hashContent | ConvertFrom-StringData $hash['request'] } # 输出结果 $requestValues
方法2:用正则直接匹配request值
如果只需要提取request字段的值,也可以直接用正则表达式匹配Line属性中的内容:
$requestValues = $2 | ForEach-Object { # 匹配request=后的字母数字内容 if ($_.Line -match 'request=(\w+)') { $matches[1] } }
更优方案:直接过滤原对象数组
如果$arraySNOW本身就是包含request属性的对象数组,不建议用Select-String,直接用Where-Object过滤原对象,效率更高且无需解析字符串:
$requestValues = $arraySNOW | Where-Object { $_.request -match $request } | Select-Object -ExpandProperty request
内容的提问来源于stack exchange,提问作者Tihomir Buncic
相关产品推荐
相关产品推荐

