0

I have a CSV file with a four headings, the most important being the IP address. What I need to do is search through a file certain file directory and all of its child files and directories to see if the IP address is NOT contained within any files. If the IP address is not contained within any of the files, add the IP address to an array, and continue checking all IP addresses. Once done, list the contents of the array.

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

It is getting stuck at the Get-Content cmdlet specifically saying

cmdlet Get-Content at command pipeline position 1
Supply values for the following parameters:
Path[0]

0

1 Answer 1

2

Get-Content has a mandatory parameter -Path that you didn't specify. That's what's causing the error you observed. However, since Select-String can read files by itself you don't need Get-Content in the first place. Also, you definiteley want to avoid reading files from an entire directory tree multiple times. Instead create a regular expression from the IP addresses in your CSV:

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

use that pattern to find the unique IP addresses that are present in the files in a single run:

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

and then use the resulting list for filtering the CSV:

$NotMonitoredArray = $csv | Where-Object { $foundIP -notcontains $_.IPAddress } |
                     Select-Object -Expand IPAddress
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.