PowerShell for Windows Admins

May 31 2018   3:43AM GMT

Splitting into pairs

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

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.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: