≡ Menu

Powershell: Split a string by white space(s)

While writing a script today, I faced a situation where I have a string like “This is my       test                string”. As you have already noticed there are more than one spaces at different places in the string. All I need to do is eliminate all spaces and fit the words alone into a array.

Since this is a split by white space operation, I tried below and got bit surprised with the output.

$string = "This is my test string"
$string.split(" ") 

Output:

The output is array which is containing the words plus some spaces in middle. This is not what I expected. After some struggle, I made it to work by using -Split.

Now the working code is…

$string = "This is my test string"
$array = $string -split "\s+"
$array

 

Output:

 

Hope this little tip helps. Visit to http://www.powershelladmin.com/wiki/Powershell_split_operator for more examples about using -Split.

[Update]:

The usage for -split is very simple and I believe this is a best suit for simple requirements like the one I showed you above. But if you have something more complex, then you may want to explore the usage of [regedit]::Split() dotnet method.