0

I am trying to write a PowerShell script to look for certain strings in a text file but not getting very far.,

What I want to do is:

  1. Search line by line until "set name 'Web Traffic Filter - General"' is found then write line to file.

  2. Once found keep looking though the file for the next line with 'set domain' is found then write line to file.

  3. Once found keep looking though the file for the next line with 'set type' is found then write line to file.

  4. Once found keep looking though the file for the next line with 'set action' is found then write line to file.

  5. Repeat though file.

Example taken from file

set name "Web Traffic Filter - General"

config entries

edit 2

set domain "*whois.com*"

set type wildcard

set action allow

next

edit 3

set domain "*lufthansa.com*"

set type wildcard

set action allow

next

edit 4

set domain "*partnerplusbenefit.com*"

set type wildcard

set action allow

next

edit 5

set domain "www.lufthansa.com"

set action allow

next

This is what I have tried but not working:

foreach($line in Get-Content C:\Scripts\test.conf) {

    # Find Policy Name
    if($line -match 'set name "Web Traffic Filter - Restricted"'){
        echo $line
        echo ############################################################
    }

    # Find set domain
    if($line -match 'set domain'){
        echo $line
    }

    # Find set type
    if($line -match 'set type'){
        echo $line
    }

    # Find set action
    if($line -match 'set action'){
        echo $line
    }
}
3
  • Try Net code : $filename = 'C:\Scripts\test.conf' $reader = [System.IO.StreamReader]::new($filename) While(($line = $reader.ReadLine()) -ne $null) { }
    – jdweng
    Commented Jul 3, 2024 at 12:23
  • Define "not working". What happens, and how does that conflict with your expectations? Commented Jul 3, 2024 at 13:13
  • Does the string search have to be in that order specifically? Commented Jul 3, 2024 at 15:15

1 Answer 1

0

Based on your description you, below is one way to achieve the objective.

$lines = Get-Content -Path 'C:\Scripts\test.conf'
$matchStrings = @('set name "Web Traffic Filter - General"',
                  'set domain',
                  'set type',
                  'set action')
$i = 0

foreach ($line in $lines) {
    if ($line -match $matchStrings[$i]) {
        Write-Host $line
        if (++$i -eq $matchStrings.Length) {
            $i = 0
        }
    }
}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.