【问题标题】:Powershell - Export-Csv prints "System.Text.RegularExpressions.Match[]" instead of the matchPowershell - Export-Csv 打印“System.Text.RegularExpressions.Match[]”而不是匹配
【发布时间】:2017-02-26 15:13:46
【问题描述】:

我写了一个搜索给定目录中所有 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 的输出如下所示:

所有其他编程语言都告诉我,括号表示数组,所以我尝试用Matches[0]替换Matches,没有骰子。

显然那些括号不是一个数组,而是一个属性或什么?有什么想法吗?

【问题讨论】:

    标签: regex powershell csv powershell-4.0


    【解决方案1】:

    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
        }
      }
    

    【讨论】:

    • 你是大师。谢谢楼主
    猜你喜欢
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 2018-02-08
    • 2019-11-01
    • 2013-02-05
    • 2021-12-11
    相关资源
    最近更新 更多