JacekK
JacekK

Reputation: 3

Get-Content with Wait and processing each line

Using -Match gives me True/False values instead of the lines of text.

Get-Content ("\\path”) -tail 10 -wait | % {
    foreach ($data in ($_ -match "Execute")) {
        $First = $data.Substring(26,37).Trim()
        Write-Host $First
    }
}

I used below code without -tail -wait to do what I, but I can't change to parsing the file using -tail with Get-Content.

$DB = Get-Content ("\\path”) -tail -ReadCount 5000000  | foreach { $_ -match "string to match" } | foreach{ $_.Trim()}  

foreach ($Data in $DB) {
    $First = $Data.Substring(26,37).Trim()
    $Second = $Data
    Write-Host $First
    Write-Host $Second
}

Upvotes: 0

Views: 1435

Answers (3)

JohnLBevan
JohnLBevan

Reputation: 24470

The -match expression returns a boolean result, but also updates a special variable, $matches.

You can filter lines by using -match in a where-object expression to return only those lines which match.

$myFilteredArray = $myArray | where-object{$_ -match 'execute'}

If using it for something that simple though, you may as well use -like:

$myFilteredArray = $myArray | where-object{$_ -like '*execute*'}

If you want to be clever, you can also use regular expressions; that way $matches will hold all captured groups (including a special group named 0 which holds the original line).

Simple Example / plain text search

@(
    'line 1 - please '
    ,'line 2 - execute'
    ,'line 3 - this'
    ,'line 4 - script'
) | where-object {$_ -match 'execute'} | foreach-object{
    "-Match found the following matches:"
    $matches
    "The line giving this result was"
    $_
} 

Example using Regex / capturing group

@(
    'line 1 - please '
    ,'line 2 - execute'
    ,'line 3 - this'
    ,'line 4 - script'
) | where-object {$_ -match '(?<capturedData>.*?)(?: - )execute'} | foreach-object{
    "-Match found the following matches:"
    $matches
    "The line giving this result was"
    $_
} 

Upvotes: 0

Vesper
Vesper

Reputation: 18747

As a workaround, you can array-cast your $_, like this:

foreach ($data in (,$_ -match "Execute")) {

Here's the output difference:

$data=@("bla bla","foo bla","foo bar","bla bar")
PS > $data | % { foreach ($a in ($_ -match "bla")){$a}}
True
True
False
True
PS > $data | % { foreach ($a in (,$_ -match "bla")){$a}}
bla bla
foo bla
bla bar

Upvotes: 1

Joey
Joey

Reputation: 354684

Well, -match when applied to a scalar returns a boolean result. When applied to an array it returns the matching elements. In your second example you use ReadCount to force Get-Content to send more than a line through the pipeline at a time. Of course you're then getting an array of lines every time instead of just a line, thus changing the semantics of -match.

To make your first example work, simply change foreach into if.

Upvotes: 0

Related Questions