Add colon between every 2 characters

by markdjones82 at 2013-02-25 13:49:57

I have some WWN’s where I am trying to parse them out to have colons between each 2 digits for example:

10000000C9748F2C needs to be 10:00:00:00:C9:74:8F:2C

Any help?
by mjolinor at 2013-02-25 14:51:01
I came up with this:
$text = ‘10000000C9748F2C’

(&{for ($i = 0;$i -lt $text.length;$i += 2)
}}) -join ‘]

by markdjones82 at 2013-02-26 07:10:14
Thanks, that did the trick! What exactly does the & at the beginning signify?
by mjolinor at 2013-02-27 12:57:38
That invokes the scriptblock that’s enclosing the for loop. The for loop normally emits the output as it’s created. The scriptblock will cause it to accumulate the output until the loop completes.
by markdjones82 at 2013-02-27 13:31:03
Ah! Thanks for the explaination, trying to teach myself to fish. I am from the linux bash world so trying to understand the syntax on powershell.

so &{} executes the script block and () encapsulates the output and allows us to do the -join against the output right?
by mjolinor at 2013-02-27 13:36:14
That’s it.
by BustedFlush at 2013-02-28 08:45:24
Is there another way to do this, maybe using a regex?
by mjolinor at 2013-02-28 09:12:21

$text = ‘10000000C9748F2C’
$text -replace ‘(…(?!$))’,’$1:‘


(it’s unusual for someone to ask for regex - most people seem to want to avoid them)
by BustedFlush at 2013-02-28 12:09:31
Ha! Is it any wonder? Look at that regex; I can’t make hide nor hair of it.

But you can see the power - your first example was elegant and worked great, but is 6 lines. The 2nd example is nearly a 1 liner!

Care to break down what the regex is doing?
by mjolinor at 2013-02-28 12:22:55
$text -replace ‘(…(?!$))’,’$1:‘

That basically translates to: Match any 2 characters (that’s the … part) that aren’t followed by end of line (that’s the (?!$) part, and replace that with the two characters followed by a colon - ‘$1:‘

An easier example might be this:

$text -replace ‘(…)’,’$1:‘

That says: "match any 2 characters, and replace it with those characters followed by a colon."

That’s also going to add a colon to the last pair, and you end up with this:


Wrapping that in parens lets you apply the string trim() function to the result, and trim off the trailing colon.

($text -replace ‘(…)’,’$1:’).trim(’:’)

by BustedFlush at 2013-02-28 12:30:13
Too cool. That is awesome, thanks!