Aug 142015
 

In this post we’ll be discussing on how to manipulate strings using PowerShell. PowerShell comes with the following string manipulation operators…

  • split – case sensitive split
  • isplit – case insensitive split
  • csplit – case sensitive split
  • join – joins an array into one string
  • replace – case sensitive split
  • ireplace – case insensitive split
  • creplace – case sensitive split
Split Demo Using Split Function Call
#store comma delimited wild animals list into a string
$wildanimals = "Tiger,Lion,Elephant,Bear,Fox,Jackal,Hyena"
#split the string using Split function based on ","
$wildanimals.Split(",")
Output
========
Tiger
Lion
Elephant
Bear
Fox
Jackal
Hyena
Split Demo Using -Split Operator
#split array using -split operator
$wildanimals -split ","
Output
========
Tiger
Lion
Elephant
Bear
Fox
Jackal
Hyena
#split into three strings, this will leave the third string unsplit
$wildanimals -split ",", 3
Output
========
Tiger
Lion
Elephant,Bear,Fox,Jackal,Hyena
#replace all "," with " "
$wildanimals = ($wildanimals -replace ",", " ")
#alternate syntax, with no split criteria the default is to use " " as split criteria
-split $wildanimals
#restore "," back instead of " "
$wildanimals = ($wildanimals -replace " ", ",")
Join Demo
#store into an array
$wildanimalsarray = $wildanimals -split ","
#join operator takes an array and makes it a string, each element separated by ","
$wildanimalsarray -join ","
Output
========
Tiger,Lion,Elephant,Bear,Fox,Jackal,Hyena
Replace Demo
#replace all instances of Elephant with Zebra
$wildanimals -replace "Elephant","Zebra"
Output
========
Tiger,Lion,Zebra,Bear,Fox,Jackal,Hyena
Conclusion

The case sensitive and insensitive operators are similar in usage except they are sensitive/insensitive to case. Hope this helps you.