Replace Space with Underscore in PowerShell

💡 TL;DR

To replace space with underscore in PowerShell, use String’s replace() method or PowerShell’s replace operator.

Here is simple example:

There are multiple ways to replace Space with Underscore in PowerShell. Let’s go through them.

Using String’s replace() method

You can use string’s replace() method to replace space with underscore in PowerShell.

Replace method returns new string and replaces each matching text with new text.
Replace methods takes two arguments:

  • substring to find in given string : space
  • replacement String for found String: underscore

Using replace operator

You can use PowerShell’s replace operator to replace space with underscore in PowerShell.

Replace operator takes two arguments:

  • substring to find in given string : space
  • replacement String for found String: underscore

As you can see, replace operator replaced all spaces with underscore in the String.

Please note that we have assigned result of replace() method or replace() operator to new string,

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *