Home > OS >  Selecting String within ForEach-Object
Selecting String within ForEach-Object

Time:11-05

How do I select only the string that matched without the if statement running through every "paragraph"? Or how do I select a value from only one input object at a time?

Here is my thought process:

# Here I have treated each rule as a "paragraph" and used a delimiter on "next". 
$content = Get-Content C:\firewallrules.txt -Delimiter 'next' 

# For every "paragraph"
$content | ForEach-Object {

    if($_ -Match 'set ips-sensor'){

        "Value Found = "   $valuefound

        # This prints every match I want to print ONLY the line that matched then iterate through the rest of the document
        # Basically, I'm trying to say if($_ -Match 'set ips-sensor') then echo that specific line
        
        $valuefound = $content | Select-String ips-sensor\s .* | % { $_.Matches.Value }
       
    }
    
    else{
        
        "Value Not Found"
         
        }
    
}

My expected output would look something like this:

Value Not Found
Value Found = ips-sensor "default"
Value Found = ips-sensor "default"
Value Not Found
Value Not Found

CodePudding user response:

Try the following:

Get-Content C:\firewallrules.txt -Delimiter 'next' | 
  ForEach-Object {
    $match = ($_ | Select-String 'ips-sensor. ').Matches.Value
    if ($match) { "Value found: $match" }
    else        { "Value not found" }
  }

Or, more efficiently, with only a -match operation, which reports its results in the automatic $Matches variable:

Get-Content t.txt -Delimiter 'next' | ForEach-Object {
  if ($_ -match 'ips-sensor. ') { "Value found: $($Matches[0])" }
  else                          { "Value not found" }
}

As for what you tried:

  • $content | Select-String ... should have been $_ | Select-String ..., because $content is the array of all paragraphs, not the paragraph at hand, as reflected in the automatic $_ variable.

  • Also, to avoid matching twice there is no need to use both -match and a Select-String call.

  • Related