Powershell 找到不同数量的数组的常见字符串

Powershell find common strings varying number of arrays

问题是 Powershell find common string in multiple files

的后续问题

以下 PowerShell 代码

  1. 遍历目录

  2. 对每个文件,提取IP地址存入多维数组$match

  3. 迭代后,遍历多维数组中的每一个元素,按space拆分,存入另一个多维数组$j

我能够找到 $j[0]$j[1] 之间的交集,但我不确定如何在数组 $j 的所有元素上迭代执行此操作IP 地址数组的数量。

见代码

$i = $NULL
$match = @()
$j = @()
$input_path = $NULL
$output_file = "D:\Script\COMMON.TXT"

$directory = "D:\Script\Files"
$regex = ‘\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b’

Get-ChildItem $directory | ForEach-Object{

    $input_path = $directory + "\" + $_.Name
    write-host $input_path
    $match += ,@(select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value })
}



foreach ($i in $match){
    $j += ,@($i.split(" "))
}

$j[0] | sort | select -Unique | where {$j[1] -contains $_} | select -Unique > $output_file

这很简单。你说你有一个二维数组 $j 并且想找到存在于 $j 的所有元素中的所有字符串。您从 $j[0] 创建一个临时 "total intersection" 数组,然后在 $j 上创建 运行 foreach 并在该临时数组中创建一个交集。最后,它将只包含所有列包含的那些元素。

# $j is two-dimensional, and has unique elements
$t=$j[0]
$j | % {
    $i=$_ #rename to avoid confusion
    if ($i -ne $j[0]) { $t = $t|where {$i -contains $_}}
}
# $t now has your intersection