【问题标题】:Search values from Txt file and Variable using Powershell使用 Powershell 从 Txt 文件和变量中搜索值
【发布时间】:2021-08-22 13:12:02
【问题描述】:

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

Host      IP             OS

Server1   192.168.1.1   Server_2016
PC1       192.168.1.1   Windows_10

尝试在文本文件中搜索操作系统并从文本文件中获取匹配结果。

文本文件有以下条目:

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 文件中匹配的 XML 属性。对吗?
  • 正确,所以我的最终结果是 HOST IP OS XML

标签: powershell powershell-2.0 powershell-3.0


【解决方案1】:

如果txt 文件和$result 将有更多数据,如果 OS 上找不到,您可以在 $xml 上添加条件>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

【讨论】:

    猜你喜欢
    • 2017-04-13
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多