1

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?

1

1 Answer 1

4

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your fast solutions!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.