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.

2 Responses to Splitting into pairs

  1. Graham Beer says:

    Thanks for explaining the reason behind putting a count in a array. I watched your video at the summit this week and really enjoyed it. I wrote an article a few weeks before that was about scriptblocks. https://4sysops.com/archives/the-powershell-scriptblock/

  2. Svilen Sultanov says:

    So if I am getting this correctly – arrays themselves are subject of the standard scope rules, but the array elements are not? Meaning you can change array elements inside a child scope, but adding new elements to the array is not possible? Why is that?

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 )

Connecting to %s