为什么我的 PowerShell 脚本没有命名匹配组?
Why does my PowerShell script not name the match groups?
我有一个小的 PowerShell 脚本,它解析日志文件以提取某些行并将它们放入 ArrayList。
[regex]$regex = "(?'datetime'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{1,3}[+-]\d{2}:\d{2}).*" #shortened for ease of understanding
$results = New-Object System.Collections.ArrayList
Get-ChildItem 'C:\debug-*.txt' | ForEach-Object {
Get-Content $_ | Where-Object {$_ -match $regex} | ForEach-Object {
$match = $regex.Match($_)
$obj = New-Object psobject
foreach ($group in $match.Groups) {
if ($group.Name -ne "0") {
$obj | Add-Member -NotePropertyName $group.Name -NotePropertyValue $group.Value
}
}
$results.Add($obj)
}
}
在我的开发 PC 上它可以工作,在一台 Windows 2012 服务器上它可以工作但在另一台上我收到错误,因为 $group.Name
为空。在那台机器上 Match
的组中从来没有 Name
属性。
这似乎是在 .NET 1.1 中添加的,但服务器是 Windows 2012,安装了 PowerShell 3.0 和 .NET 4。
答案是以不同的方式构造循环并使用 $Matches
哈希表而不是 Group
对象。
$tmp = $_ -match $regex
foreach ($match in $matches) {
if ($match -ne "0") {
$obj | Add-Member -NotePropertyName $match -NotePropertyValue $matches[$match]
}
}
我不清楚 $matches
的来源,但它有效。
我有一个小的 PowerShell 脚本,它解析日志文件以提取某些行并将它们放入 ArrayList。
[regex]$regex = "(?'datetime'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{1,3}[+-]\d{2}:\d{2}).*" #shortened for ease of understanding
$results = New-Object System.Collections.ArrayList
Get-ChildItem 'C:\debug-*.txt' | ForEach-Object {
Get-Content $_ | Where-Object {$_ -match $regex} | ForEach-Object {
$match = $regex.Match($_)
$obj = New-Object psobject
foreach ($group in $match.Groups) {
if ($group.Name -ne "0") {
$obj | Add-Member -NotePropertyName $group.Name -NotePropertyValue $group.Value
}
}
$results.Add($obj)
}
}
在我的开发 PC 上它可以工作,在一台 Windows 2012 服务器上它可以工作但在另一台上我收到错误,因为 $group.Name
为空。在那台机器上 Match
的组中从来没有 Name
属性。
这似乎是在 .NET 1.1 中添加的,但服务器是 Windows 2012,安装了 PowerShell 3.0 和 .NET 4。
答案是以不同的方式构造循环并使用 $Matches
哈希表而不是 Group
对象。
$tmp = $_ -match $regex
foreach ($match in $matches) {
if ($match -ne "0") {
$obj | Add-Member -NotePropertyName $match -NotePropertyValue $matches[$match]
}
}
我不清楚 $matches
的来源,但它有效。