Monthly Archive

Categories

Splitting into pairs

During my session on scriptblocks at Summit 2018 I showed how to split a string into pairs of values

Start with this string

PS> $str = 'Jack,Jill,Bill,Ben,Eric,Ernie,Cagney,Lacey'

 

You want the string split in the commas – but every other comma so you get pairs if values separated by a comma.

You need to set a counter
PS> $count=@(0)
PS> $count
0

 

Then use a scriptblock to control the split
PS> $str -split {$_ -eq ',' -AND ++$count[0] % 2 -eq 0}
Jack,Jill
Bill,Ben
Eric,Ernie
Cagney,Lacey
PS> $count
7

 

You need to use an array because the scriptblock executes in its own context and a scalar value wouldn’t be updated as you need.

Try

PS> $count2 = 0
PS> $str -split {$_ -eq ',' -AND ++$count2 % 2 -eq 0}
Jack,Jill,Bill,Ben,Eric,Ernie,Cagney,Lacey
PS> $count2
0

and nothing happens.

Comments are closed.