【问题标题】:Query and list strings not found within file directory查询和列出文件目录中未找到的字符串
【发布时间】:2016-04-18 14:17:22
【问题描述】:

我有一个包含四个标题的 CSV 文件,其中最重要的是 IP 地址。我需要做的是搜索某个文件目录及其所有子文件和目录的文件,以查看 IP 地址是否不包含在任何文件中。如果 IP 地址不包含在任何文件中,请将 IP 地址添加到数组中,然后继续检查所有 IP 地址。完成后,列出数组的内容。

$Path = "C:\Users\Me\Desktop\nagios\configs\hosts"
$NotMonitoredArray = @()

$servers = Import-Csv "C:\wpg-export.csv" 
foreach ($item in $servers) {
    Get-ChildItem $Path -Recurse | Where-Object {
        $_.Attributes -ne "Directory"
    } | ForEach-Object {
        if (Get-Content | Where-Object { !(Select-String -Pattern $_.IPAddress -Quiet) }) {
            $NotMonitoredArray += $_.IPAddress
        }
    }
}

它卡在Get-Content cmdlet 上,特别是说

cmdlet Get-Content 在命令管道位置 1
提供以下参数的值:
路径[0]

【问题讨论】:

    标签: powershell


    【解决方案1】:

    Get-Content 有一个您未指定的强制参数 -Path。这就是导致您观察到的错误的原因。但是,由于Select-String 可以自己读取文件,因此您首先不需要Get-Content。此外,您肯定希望避免多次从整个目录树中读取文件。而是从 CSV 中的 IP 地址创建一个正则表达式:

    $csv = Import-Csv 'C:\wpg-export.csv'
    $pattern = ($csv | ForEach-Object {
                 '({0})' -f [regex]::Escape($_.IPAddress)
               }) -join '|'
    

    使用该模式在一次运行中查找文件中存在的唯一 IP 地址:

    $foundIP = Get-ChildItem $Path -Recurse |
               Where-Object { -not $_.PSIsContainer } |
               Select-String -Pattern $pattern |
               Select-Object -Expand Matches |
               Select-Object -Expand Value -Unique
    

    然后使用结果列表过滤 CSV:

    $NotMonitoredArray = $csv | Where-Object { $foundIP -notcontains $_.IPAddress } |
                         Select-Object -Expand IPAddress
    

    【讨论】:

      猜你喜欢
      • 2015-07-23
      • 2013-07-06
      • 1970-01-01
      • 2014-12-19
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      • 2015-04-04
      • 1970-01-01
      相关资源
      最近更新 更多