PS without BS: multiple replace of a string


Been a busy blog day, but the last one today (promise). There is feature that is unique to PowerShell that makes it better than say your old VB/VBScript and really sets it apart.

To replace text in a string multiple times in VBScript, you had to do something like the following:
dim string1 as string
String1="Some text needs to be replaced"
String1=Replace(String1,"Some","Not All")
String1=Replace(String1,"needs","should be")

In PowerShell (starting in v3), you can actually combine these into one statement by using multiple replace commands:
$string1="Some text needs to be replaced"
$string1=$string1.Replace("Some","Not All").Replace("needs","should be")

Your output from PowerShell: Not All text should be replaced

Great time saving tip in a pinch. Happy scripting.

-- If you like my blogs, please share it on social media, rate it, and/or leave a comment. --


Comments (5)

  1. This method can lead to long lines of code…
    Did you compare the speed execution of both methods?

    1. leecstevens says:

      I would certainly agree with you, Luc. It can lead to some long lines of code, but for a simple transaction as this, not so bad. Personally, I can’t stand having to scroll across a screen reading code, I’m with you 🙂

      For speed, however, this post was more meant to show off simplicity of how PowerShell acts versus something like VBScript. For this transaction, performance is indeterminate to the naked eye. For 100,000 transactions, not sure. I suppose that’s something I can test and see later on.

      1. I tried with 100,000 transactions (10,000 was not enough to make it significant and have a stable result).
        In fact both methods are very close in speed.
        Around 450 milliseconds for the first one, and 570 for the second one.
        Like you said: “indeterminate to the naked eye” 🙂

        1. leecstevens says:

          Thank you, Luc, appreciate you for doing this. But some may argue with you that they can determine what 120ms looks like. 🙂

          I still agree with your point about the long lines of code though, beware of sloppy scripting.

  2. turbomcp says:

    Thanks
    very nice

Skip to main content