Powershell - Export-Csv 打印 "System.Text.RegularExpressions.Match[]" 而不是匹配项
Powershell - Export-Csv prints "System.Text.RegularExpressions.Match[]" instead of the match
我编写了一个函数来搜索给定目录中的所有 IP:
function searchips
{
param(
[Parameter(Mandatory=$false)][string]$dir = $(pwd)
)
ls -Recurse -Force `
| Select-String -Pattern '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' -AllMatches `
| ? {
$matches = ($_.Matches | Select-Object -Unique)
return $matches.Count -gt 1 -or $matches[0].Value -ne '127.0.0.1'
} `
| select Path,Matches,FileName,LineNumber,Line
}
当我尝试将输出通过管道传输到 CSV 时,除了 Matches 列之外,一切都很好:
我的电话:searchips | Export-Csv outfile.csv
我在目录中调用这个
不要尝试在目录外调用它,因为它在 pwd
中总是 运行。仍然需要修复...
它在下面吐出 outfile.csv
...
如您所见,我在 CSV 的 Matches 列中得到 System.Text.RegularExpressions.Match[]
。
在 ISE 中,没有 管道到 Export-Csv
的输出 看起来像这样:
所有其他编程语言都告诉我 brackets 意思是 array,所以我尝试用 [=18= 替换 Matches
] 没有骰子。
显然那些括号不是数组,而是 属性 之类的东西?有什么想法吗?
Matches
是一个集合,但是不能在Select-Object
中使用Matches[0]
,因为它不是一个属性。使用 calculated property 从包含集合的 属性 中获取值。
如果你只想要第一场比赛,你可以使用这样的东西:
select Path, @{n='Matches';e={$_.Matches[0].Value}}, FileName, LineNumber, Line
如果您希望所有匹配项都作为字符串使用,请使用如下内容:
select Path, @{n='Matches';e={$_.Matches.Groups.Value -join '|'}}, FileName,
LineNumber, Line
如果您希望每场比赛都作为单独的记录,您需要这样的东西:
ForEach-Object {
foreach ($ip in $_.Matches.Groups.Value) {
New-Object -Type PSObject -Property @{
Path = $_.Path
Match = $ip
FileName = $_.FileName
LineNumber = $_.LineNumber
Line = $_.Line
}
}
我编写了一个函数来搜索给定目录中的所有 IP:
function searchips
{
param(
[Parameter(Mandatory=$false)][string]$dir = $(pwd)
)
ls -Recurse -Force `
| Select-String -Pattern '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' -AllMatches `
| ? {
$matches = ($_.Matches | Select-Object -Unique)
return $matches.Count -gt 1 -or $matches[0].Value -ne '127.0.0.1'
} `
| select Path,Matches,FileName,LineNumber,Line
}
当我尝试将输出通过管道传输到 CSV 时,除了 Matches 列之外,一切都很好:
我的电话:searchips | Export-Csv outfile.csv
我在目录中调用这个
不要尝试在目录外调用它,因为它在
pwd
中总是 运行。仍然需要修复...
它在下面吐出 outfile.csv
...
如您所见,我在 CSV 的 Matches 列中得到 System.Text.RegularExpressions.Match[]
。
在 ISE 中,没有 管道到 Export-Csv
的输出 看起来像这样:
所有其他编程语言都告诉我 brackets 意思是 array,所以我尝试用 [=18= 替换 Matches
] 没有骰子。
显然那些括号不是数组,而是 属性 之类的东西?有什么想法吗?
Matches
是一个集合,但是不能在Select-Object
中使用Matches[0]
,因为它不是一个属性。使用 calculated property 从包含集合的 属性 中获取值。
如果你只想要第一场比赛,你可以使用这样的东西:
select Path, @{n='Matches';e={$_.Matches[0].Value}}, FileName, LineNumber, Line
如果您希望所有匹配项都作为字符串使用,请使用如下内容:
select Path, @{n='Matches';e={$_.Matches.Groups.Value -join '|'}}, FileName,
LineNumber, Line
如果您希望每场比赛都作为单独的记录,您需要这样的东西:
ForEach-Object {
foreach ($ip in $_.Matches.Groups.Value) {
New-Object -Type PSObject -Property @{
Path = $_.Path
Match = $ip
FileName = $_.FileName
LineNumber = $_.LineNumber
Line = $_.Line
}
}