Monthly Archive

Categories

PowerShell join

I looked at PowerShell split a few posts back. This time I’ll look at the opposite action – PowerShell join.

Lets look at a simple string

PS> $str = 'PowerShell for Windows and Linux'

and split it

PS> $strs = -split $str
PS> $strs
PowerShell
for
Windows
and
Linux

 

You end up with an array of strings.

Now lets put it back together again

You can just use the operator

PS> -join $strs
PowerShellforWindowsandLinux

 

but there’s no delimiter (default) between the elements as they’re joined. You can define a delimiter

PS> $strs -join ' '
PowerShell for Windows and Linux
PS> $strs -join '_'
PowerShell_for_Windows_and_Linux

 

And that’s it for join.

Beware that you can use variable substitution to effect a join

PS> "$strs"
PowerShell for Windows and Linux

 

Also be aware that if you give the join operator a comma-separated list the join will fail

PS> -join 'PowerShell', 'for', 'Windows', 'and', 'Linux'
PowerShell
for
Windows
and
Linux

 

because join has a higher operator precedence than comma

You need to wrap the list in parentheses

PS> -join ('PowerShell', 'for', 'Windows', 'and', 'Linux')
PowerShellforWindowsandLinux

or use a variable as you saw earlier
PS> $x = 'PowerShell', 'for', 'Windows', 'and', 'Linux'
PS> -join $x
PowerShellforWindowsandLinux

 

Using a delimiter also works

PS> 'PowerShell', 'for', 'Windows', 'and', 'Linux' -join ' '
PowerShell for Windows and Linux
PS> ('PowerShell', 'for', 'Windows', 'and', 'Linux') -join ' '
PowerShell for Windows and Linux

Comments are closed.