Home > Mobile >  Powershell: Insert multiple chars into a string with a loop
Powershell: Insert multiple chars into a string with a loop

Time:09-17

I want to insert ":" after every second character - the end result should look like this 51:40:2e:c0:11:0b:3e:3c.

My solution

$s = "51402ec0110b3e3c"

for ($i = 2; $i -lt $s.Length; $i =3)
{
$s.Insert($i,':')
}

Write-Host $s

returns

51:402ec0110b3e3c
51402:ec0110b3e3c
51402ec0:110b3e3c
51402ec0110:b3e3c
51402ec0110b3e:3c
51402ec0110b3e3c

Why is $s being returned multiple times when I only put Write-Host at the very end? Also, it looks like $s keeps returning to its original value after every loop, overwriting the previous loops...

I would've thought that the loop accomplishes the same as this:

$s = $sInsert(2,':').Insert(5,':').Insert(8,':').Insert(11,':').Insert(14,':').Insert(17,':').Insert(20,':')

CodePudding user response:

This is because insert returns a new string. It does not modify inplace. So you have to change

$s.Insert($i,':') 

to

$s = $s.Insert($i,':')

CodePudding user response:

You can also do this without looping via the -replace operator:

$s = "51402ec0110b3e3c"
$s = $s -replace '..(?!$)','$0:'

A combination of -split and -join works too:

$s = "51402ec0110b3e3c"
$s = $s -split '(..)' -ne '' -join ':'

CodePudding user response:

an alternate method for converting a hex string to a colon-delimited string is to use the -split operator with a pattern that specifies two consecutive characters. this ...

$s = "51402ec0110b3e3c"
($s -split '(..)').Where({$_}) -join ':'

... will give this = 51:40:2e:c0:11:0b:3e:3c.

the .Where() filters out the blank entries the split leaves behind. [grin]

take care,
lee

  • Related