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.

Advertisements
This entry was posted in Powershell. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s