Freigeben über


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

  • Anonymous
    June 09, 2017
    The comment has been removed
    • Anonymous
      June 10, 2017
      The comment has been removed
      • Anonymous
        June 15, 2017
        The comment has been removed
        • Anonymous
          June 16, 2017
          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.
  • Anonymous
    June 10, 2017
    Thanksvery nice