Replacing Part of String at Position in Powershell

Right now i'm trying to convert my C# Code to an PowerShell Script.

My actual function in C# 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 PowerShell function like this:

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

But i alway get an [System.Text.StringBuilder] as return value.

What do i miss to make the function work again?

Upvotes: 1

Views: 1905

Answers (1)

Lance U. Matthews
Lance U. Matthews

Reputation: 16612

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) `
    .ToString();

Upvotes: 4

Related Questions