NathanK
NathanK

Reputation: 101

Powershell Multiple StartsWith clauses

I'm stripping lines out of a file that start with '713', '714', etc. I'm currently doing so like this:

$stripped = $stripped | where{-Not $_.StartsWith('713')}
$stripped = $stripped | where{-Not $_.StartsWith('714')}
$stripped = $stripped | where{-Not $_.StartsWith('715')}
$stripped = $stripped | where{-Not $_.StartsWith('716')}
$stripped = $stripped | where{-Not $_.StartsWith('717')}

This feels super-sloppy. How can I improve this code?

Upvotes: 2

Views: 4633

Answers (1)

Matt
Matt

Reputation: 46710

Few things would work here. First we could use array notation with your number sequence and the operator -notin. We need to extract the first charaters for a simple comparison in order for this to work.

$stripped = $stripped | Where{$_.substring(0,3) -notin (713..717)}

So if the first 3 characters are in the number range then they are skipped.

For other solutions we could use regex since there is a noticeable pattern in your numbers. You could use a pattern to not match numbers from 713 - 717 that are at the beginning of the string.

$stripped = $stripped | where{$_ -notmatch "^71[3-7]"}

Let says there was not a pattern and you just didn't want any of a series of strings at the beginning.

$dontMatchMe = "^(" + ("Test","Bagel","123" -join "|") + ")"
$stripped = $stripped | where{$_ -notmatch $dontMatchMe}

The caret ^ is a regex anchor for the beginning of the string. So we build an array of string that we don't want and join them with a pipe character and enclose it in brackets. It would look like this in my example:

PS C:\Users\Cameron> $dontMatchMe
^(Test|Bagel|123)

You need to be careful with your string in case they contain an regex control characters.


If Regular expressions are new to you I found RexEgg to be a good reference when I got started.

Upvotes: 6

Related Questions