使用 Powershell 从 Txt 文件和变量中搜索值

Search values from Txt file and Variable using Powershell

我在变量 $result 中有以下值。

Host      IP             OS

Server1   192.168.1.1   Server_2016
PC1       192.168.1.1   Windows_10

正在尝试在文本文件中搜索 OS 并从 Txt 文件中获取匹配结果。

文本文件包含以下条目:

CIS_Windows_10_(Release_1607)Benchmark.xml CIS_Windows_Server_2016(Release_1607)_Benchmark.xml

已尝试遵循代码但无法从中找到,还需要文件名。

$File1 = $result.os
$File2 = Get-Content C:\Textfile.txt

$RegEx = "("
ForEach ($Line in $File1)
{
    $RegEx += "$Line|"
}
$RegEx = [regex]"$($RegEx.SubString(0,($RegEx.Length - 1))))"   #trim the last | out, we don't need it

$Search = $File2 | Select-String -Pattern $RegEx -AllMatches

ForEach($Match in $Search.Matches)
{
   Write-Output "$($Match.Value) was found in File2"
}
Desired Result :

Host      IP             OS            XML

Server1   192.168.1.1   Server_2016  CIS_Windows_Server_2016_(Release_1607)_Benchmark.xml
PC1       192.168.1.1   Windows_10   CIS_Windows_10_(Release_1607)_Benchmark.xml

如果 txt 文件和 $result 将有更多数据,您可以在 $xml 上添加条件,如果 [=28=在 txt 文件中找不到]:

$xml = $txt | Where-Object {
    $_ -match $line.OS
}

$xml = if(-not $xml)
{
    "{0} not found on txt file" -f $line.OS
}
$txt = Get-Content C:\Textfile.txt

# Using $result as the initial object
# with properties Host, IP & OS

# This is just for testing
$result = @'
Host,IP,OS
Server1,192.168.1.1,Server_2016
PC1,192.168.1.1,Windows_10
'@ | ConvertFrom-Csv

foreach($line in $result)
{
    # Where each line of $txt matches THIS $line.OS
    $xml = $txt | Where-Object {
        $_ -match $line.OS
    }

    [pscustomobject]@{
        Host = $line.Host
        IP = $line.IP
        OS = $line.OS
        XML = $xml
    }
}

输出

Host    IP          OS          XML                                                
----    --          --          ---                                                
Server1 192.168.1.1 Server_2016 CIS_Windows_Server_2016(Release_1607)_Benchmark.xml
PC1     192.168.1.1 Windows_10  CIS_Windows_10_(Release_1607)Benchmark.xml