Smartis Smartis - 11 months ago 95
PowerShell Question

Replacing Part of String at Position in Powershell

Right now i'm trying to convert my

Code to an

My actual function in
looks like this:

private static string ReplaceStringPartAt(string mainstring, int position, string replacement)
StringBuilder strBuilder = new StringBuilder(mainstring);
strBuilder.Remove(position, replacement.Length);
strBuilder.Insert(position, replacement);
return strBuilder.ToString();

And my
function like this:

function ReplaceStringPartAt($mainstring, $position, $replacement)
$strBuilder = New-Object System.Text.StringBuilder;
$strBuilder.Remove($position, $replacement.Length);
$strBuilder.Insert($position, $replacement);
return $strBuilder.ToString();

But i alway get an
as return value.

What do i miss to make the function work again?

Answer Source

Many of the methods of the StringBuilder class return the same StringBuilder instance so you can chain multiple calls together. This is harmless in C#, but in PowerShell you need to explicitly capture these return values so they don't appear in your function output. You can either pipe them to Out-Null...

$strBuilder.AppendLine($mainstring) | Out-Null
$strBuilder.Remove($position, $replacement.Length) | Out-Null;
$strBuilder.Insert($position, $replacement) | Out-Null;

...or cast them to [Void]...

[Void] $strBuilder.AppendLine($mainstring)
[Void] $strBuilder.Remove($position, $replacement.Length);
[Void] $strBuilder.Insert($position, $replacement);

...or chain all of the calls (including .ToString()) together...

return $strBuilder.AppendLine($mainstring) `
    .Remove($position, $replacement.Length) `
    .Insert($position, $replacement) `