Table of Contents
💡 TL;DR
To replace space with underscore in PowerShell, use String’s replace() method or PowerShell’s replace operator.
Here is simple example:
1234567 $countries= "India China Bhutan Russia"$countriesWithUnderscore = $countries.Replace(" ","_")$countriesWithUnderscore#Output : India_China_Bhutan_Russia
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
1 2 3 4 5 6 7 |
$countries= "India China Bhutan Russia" $countriesWithUnderscore = $countries.Replace(" ","_") $countriesWithUnderscore #Output : India_China_Bhutan_Russia |
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
1 2 3 4 5 6 7 |
$countries= "India China Bhutan Russia" $countriesWithUnderscoreOpr = $countries -replace " ","_" $countriesWithUnderscoreOpr #Output : India_China_Bhutan_Russia |
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,