Issue with Insert function

Hi,

I am having hard time using the insert function in powershell inside a loop. Currently I am trying to Insert string to existing string at particular index values. Here is code for the same.

$data = "admin"
$count = 0
for($i=0; $i -lt $data.Length -1 ; $i++ ){
    $data = $data.Insert($i,"XX")
    Write-Host "HERE"
}

Write-Host $data

But it goes into infinite-loop and prints “HERE” constantly. My end goal is to add string to existing string at particular index with some condition( But for now I am trying to achieve this to all characters)

Any suggestion/approach to achieve this are appriciated

Thanks

Your problem is due to the fact that the length is increasing with each interation so $i will always be less than $data.length -1 so it loops forever.

You need to calculate the final length of the string and stop there, you also need to increment by the number of characters in your string to be inserted rather than increment by 1 ($i++).

Something like this:

$data = 'admin'

$insertString = 'XX'

$finalLength = $data.Length + ($insertString.Length * $data.Length -1)

for ($i = 1; $i -lt $finalLength; $i = $i + $insertString.Length + 1 ) {

    $data = $data.Insert($i,$insertString)

}

Write-Host $data

 

Why are we doing a loop at all? If you are

trying to Insert string to existing string at particular index values
what part of that suggests a loop?

"existing string".Insert(8," i was inserted")

existing i was inserted string

Because OP said [quote quote=263331]My end goal is to add string to existing string at particular index with some condition( But for now I am trying to achieve this to all characters)[/quote]

My interpretation of that together with his original code was that he wanted to insert the string after each character.

Hello Matt Bloomfield,

Sorry for late reply. You were right, I need to increase the total length to stop infinite loop. That solved the issue. Do you know by any chance, Insert function can throw any errors? because I tried playing around it but there were no exceptions on it.

Thanks

According to the documentation it throws two exceptions:

ArgumentNullException
value is null.

ArgumentOutOfRangeException
startIndex is negative or greater than the length of this instance.

try { 
    'hello'.Insert()  
}

catch {
    $error[0].Exception
}

try { 
    'hello'.Insert(6,' world')  
}

catch {
    $error[0].Exception
}