Replace Space with Comma in PowerShell

💡 TL;DR

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

Here is simple example:

$countries= "India China Bhutan Russia"
$countriesWithComma = $countries.Replace(" ",",")
$countriesWithComma

#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

Use string’s replace() method to replace space with comma in PowerShell.

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

  • substring to find in given string : space
  • replacement String for found substring: comma
$countries= "India China Bhutan Russia"
$countriesWithComma = $countries.Replace(" ",",")
$countriesWithComma

#Output : India,China,Bhutan,Russia

Using replace operator

to replace space with comma in PowerShell, use PowerShell’s replace operator .

Replace operator takes two arguments:

  • substring to find in given string : space
  • replacement String for found String: comma
$countries= "India China Bhutan Russia"
$countriesWithCommaOpr =  $countries -replace " ",","
$countriesWithCommaOpr

#Output : India,China,Bhutan,Russia

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

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

That’s all about how to replace space with comma in PowerShell.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.