Question

This piece of code actually works, and I'm curious whether I got lucky(!?) and found a bug in the Power Shell language (this is pseudo code-ish, but it illustrates my question):

$regex = "prefix([0-9]+)"
$collection = Get-Collection | Where-Object {$_.Name -match $regex} `
                             | ForEach-Object { [int] $Matches[1] }

Input is basically objects whose property Name may be on the format "prefix[Integer]". If that is the case, I want to extract that integer and insert it into a new sequence.

This seemingly works, but it feels like I'm exploiting an implementation detail in the Power Shell language.

How would you solve this problem?

Was it helpful?

Solution

The issue is that each pipeline expression is a closure.

Where-Object is only going to send the Item that matched down the pipeline, not the context.

The simplest to understand method is to do:

Get-Collection | ForEach-Object { if($_.Name -match $regex) { [int] $Matches[1] } }

OTHER TIPS

You're not exploiting anything here, it looks perfectly valid to me.

  1. You get a collection of objects
  2. You filter out the ones which match your regex using Where-Object
  3. You pass the filtered objects to a ForEach-Object loop which simply states the regex match in the pipeline as an integer.

Perfectly normal code. What's the problem?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top