6

First, make some example files:

2010..2015 | % { "" | Set-Content "example $_.txt" }

#example 2010.txt                                                                          
#example 2011.txt                                                                          
#example 2012.txt                                                                          
#example 2013.txt                                                                          
#example 2014.txt                                                                          
#example 2015.txt

What I want to do is match the year with a regex capture group, then reference the match with $matches[1] and use it. I can write this to do both in one scriptblock, in one cmdlet, and it works fine:

gci *.txt | foreach { 

    if ($_ -match '(\d+)')       # regex match the year
    {                            # on the current loop variable
        $matches[1]              # and use the capture group immediately
    } 

}
#2010
#2011
#.. etc

I can also write this to do the match in one scriptblock, and then reference $matches in another cmdlet's scriptblock later on:

gci *.txt | where { 

    $_ -match '(\d+)'     # regex match here, in the Where scriptblock

} | foreach {             # pipeline!

    $matches[1]           # use $matches which was set in the previous 
                          # scriptblock, in a different cmdlet
}

Which has the same output and it appears to work fine. But is it guaranteed to work, or is it undefined and a coincidence?

Could 'example 2012.txt' get matched, then buffered. 'example 2013.txt' gets matched, then buffered. | foreach gets to work on 'example 2012.txt' but $matches has already been updated with 2013 and they're out of sync?

I can't make them fall out of sync - but I could still be relying on undefined behaviour.

(FWIW, I prefer the first approach for clarity and readability as well).

4
  • Aside from the pipeline effects, even your first script gave me a number of 2016 because the $_ catched my LastWriteTimer so $_.Name -match '(\d{4})'would be a better RegEx. But a very good question indeed.
    – user6811411
    Dec 1, 2016 at 23:05
  • @LotPings I created the files today and they didn't trigger on LastWriteTime for me. If I run gci *.txt | %{ $_ -match '.*'; $matches[0] } to match everything and output it, I get just the path and filename and nothing else, as I'd expect. How did you run it? Dec 1, 2016 at 23:58
  • 2
    What @LotPings describes happens only with PowerShell Core, such as on macOS, and it may be a bug - at the very least, it's an inconsistency: with PowerShell Core on macOS 10.12.1, as of v6.0.0-alpha.13, it seems that when $_ is forced into a string context in the context of using the -match operator in the given command, it expands differently than on Windows PowerShell (on macOS it expands as it would when outputting to the console, as opposed to how it should in string interpolation).
    – mklement0
    Dec 2, 2016 at 0:08
  • I have a german locale and my shortdate format is 2016-12-01, since $_ gives a dir like output -a---- 2016-12-01 23:47 2 example 2012.txt matches[1] was 2016 here.
    – user6811411
    Dec 2, 2016 at 0:09

2 Answers 2

8

There is no synchronization going on, per se. The second example works because of the way the pipeline works. As each single object gets passed along by satisfying the condition in Where-Object, the -Process block in ForEach-Object immediately processes it, so $Matches hasn't yet been overwritten from any other -match operation.

If you were to do something that causes the pipeline to gather objects before passing them on, like sorting, you would be in trouble:

gci *.txt | where { 

    $_ -match '(\d+)'     # regex match here, in the Where scriptblock

} | sort | foreach {             # pipeline!

    $matches[1]           # use $matches which was set in the previous 
                          # scriptblock, in a different cmdlet
}

For example, the above should fail, outputting n objects, but they will all be the very last match.

So it's prudent not to rely on that, because it obscures the danger. Someone else (or you a few months later) may not think anything of inserting a sort and then be very confused by the result.

As TheMadTechnician pointed out in the comments, the placement changes things. Put the sort after the part where you reference $Matches (in the foreach), or before you filter with where, and it will still work as expected.

I think that drives home the point that it should be avoided, as it's fairly unclear. If the code changes in parts of the pipeline you don't control, then the behavior may end up being different, unexpectedly.


I like to throw in some verbose output to demonstrate this sometimes:

Original

gci *.txt | where { 
    "Where-Object: $_" | Write-Verbose -Verbose
    $_ -match '(\d+)'     # regex match here, in the Where scriptblock

} | foreach {             # pipeline!
    "ForEach-Object: $_" | Write-Verbose -Verbose
    $matches[1]           # use $matches which was set in the previous 
                          # scriptblock, in a different cmdlet
}

Sorted

gci *.txt | where { 
    "Where-Object: $_" | Write-Verbose -Verbose
    $_ -match '(\d+)'     # regex match here, in the Where scriptblock

} | sort | foreach {             # pipeline!
    "ForEach-Object: $_" | Write-Verbose -Verbose
    $matches[1]           # use $matches which was set in the previous 
                          # scriptblock, in a different cmdlet
}

The difference you'll see is that in the original, as soon as where "clears" an object, foreach gets it right away. In the sorted, you can see all of the wheres happening first, before foreach gets any of them.

sort doesn't have any verbose output so I didn't bother calling it that way, but essentially its Process {} block just collects all of objects so it can compare (sort!) them, then spits them out in the End {} block.


More examples

First, here's a function that mocks Sort-Object's collection of objects (it doesn't actually sort them or do anything):

function mocksort {
[CmdletBinding()]
param(
    [Parameter(
        ValueFromPipeline
    )]
    [Object]
    $O
)

    Begin {
        Write-Verbose "Begin (mocksort)"

        $objects = @()
    }

    Process {
        Write-Verbose "Process (mocksort): $O (nothing passed, collecting...)"

        $objects += $O
    }

    End {
        Write-Verbose "End (mocksort): returning objects"

        $objects
    }
}

Then, we can use that with the previous example and some sleep at the end:

gci *.txt | where { 
    "Where-Object: $_" | Write-Verbose -Verbose
    $_ -match '(\d+)'     # regex match here, in the Where scriptblock

} | mocksort -Verbose | foreach {             # pipeline!
    "ForEach-Object: $_" | Write-Verbose -Verbose
    $matches[1]           # use $matches which was set in the previous 
                          # scriptblock, in a different cmdlet
} | % { sleep -milli 500 ; $_ }
7
  • 1
    Spectacular answer, I just wanted to add that many times it just comes down to placement. If you move the Sort before the Where it may be a touch slower, but it no longer breaks the logic. Same if you move it after the ForEach-Object scriptblock. Dec 1, 2016 at 21:43
  • If you change the foreach {} code in the no-sort first example so it prints, sleeps, prints again - e.g. foreach { "$_, $($matches[1])"; start-sleep 1; "$_, $($matches[1])" } then what you get is delayed doubled output, but still all matched up. The foreach block is asleep for long enough for where to process all the remaining items, but that doesn't happen. The where block hasn't run(?), and $matches hasn't changed by the time the foreach wakes up. How does where know whether you're piping it to a buffering cmdlet, or a non-buffering cmdlet? Dec 1, 2016 at 21:44
  • @TheMadTechnician yes absolutely, that's also what makes it dangerous!
    – briantist
    Dec 1, 2016 at 21:44
  • 1
    where|sort sends all 5 things to sort, even while sort "is still running". where|foreach {sleep} doesn't act like that, proof: $matches is unchanged when foreach wakes up - where has not done anything in that time. I get it now - Process vs End. a) All begin {} blocks. b) one thing fed to every process {} in pipeline, single thread. c) finally, end {} blocks drain into remaining pipeline as new process {} input. Repeat b) c) until done. So where|sort - sort finishes process{} and where runs again. where|foreach{sleep} makes process {} blocking and where "waits". Dec 1, 2016 at 23:44
  • 2
    i.e. if the cmdlets only output from their process {} blocks, then my match/$matches pair in different places will work by virtue of the pipeline being single threaded, but if they output from end {} then match/$matches in different places won't work. Since that distinction depends on knowing the inner workings of every cmdlet, it's Not guaranteed to work, don't use. "It breaks encapsulation and modularity principles wrt treating the cmdlets as isolated components". Thanks @briantist. Dec 1, 2016 at 23:52
4

To complement briantist's great answer:

Aside from aggregating cmdlets such as Sort-Object (cmdlets that (must) collect all input first, before producing any output), the -OutBuffer common parameter can also break the command:

gci *.txt | where -OutBuffer 100 { 

    $_ -match '(\d+)'     # regex match here, in the Where scriptblock

} | foreach {             # pipeline!

    $matches[1]           # use $matches which was set in the previous 
                          # scriptblock, in a different cmdlet
}

This causes the where (Where-Object) cmdlet to buffer its first 100 output objects until the 101th object is generated, and only then send these 101 objects on, so that $matches[1] in the foreach (ForEach-Object) block will in this case only see the 101th (matching) filename's capture-group value, in every of the (first) 101 iterations.

Generally, with an -OutputBuffer value of N, the first N + 1 foreach invocations would all see the same $matches value from the (N + 1)-th input object, and so forth for subsequent batches of N + 1 objects.

From Get-Help about_CommonParameters:

When you use this parameter, Windows PowerShell does not call the next cmdlet in the pipeline until the number of objects generated equals OutBuffer + 1. Thereafter, it sends all objects as they are generated.

Note that the last sentence suggests that only the first N + 1 objects are subject to buffering, which, however, is not true, as the following example (thanks, @briantist) demonstrates:

1..5 | % { Write-Verbose -vb $_; $_ } -OutBuffer 1 | % { "[$_]" }
VERBOSE: 1
VERBOSE: 2
[1]
[2]
VERBOSE: 3
VERBOSE: 4
[3]
[4]
VERBOSE: 5
[5]

That is, -OutBuffer 1 caused all objects output by % (ForEach-Object) to be batched in groups of 2, not just the first 2.

4
  • 1
    This is fantastic! I've managed to completely ignore this parameter forever somehow. I love learning new things like this. And I can think of a (small) few situations where I might have actually used it.
    – briantist
    Dec 1, 2016 at 23:48
  • mklement0 Interesting, I didn't know OutputBuffer was a thing. What's it useful for? @briantist ... like when might you have used it? Dec 1, 2016 at 23:56
  • 2
    Here's a quick thing I did to satisfy my curiosity: 1..100 | % { Write-Verbose $_ -Verbose ; $_ } -OutBuffer 50 | select -f 10. In PSv3, cmdlets got the ability to stop the pipeline, so adding something like select -first 1 would stop the whole pipeline after the first object. In v2, it would output the first object only, but still process all of the remaining. As expected, using a buffer will prevent these cmdlets from stopping any shorter than the previous buffer size.
    – briantist
    Dec 2, 2016 at 0:00
  • 2
    @TessellatingHeckler as we've seen with inserting sleeps, commands down the pipeline can slow down processing of the whole pipeline. Depending on what you're doing. If early commands are time sensitive, buffering may offer better efficiency and this gives you a way to do it. It gives more control over the process. Also note that one specific function in the pipeline can return multiple objects. These are processed one at a time as well. That could be very bad if later elements interrupt and the op is supposed to be atomic. Knowing you return 3 objs on every call, you can -OutBuffer 3.
    – briantist
    Dec 2, 2016 at 0:07

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.