Monthly Archive

Categories

Join-String

Join-String is a new cmdlet in PowerShell v6.2 preview 3. Join-String enables you to use the pipeline to join strings.

 

We’ve had the –join operator for a long time:

PS> 1..3 -join ','
1,2,3

 

As an alternative you could do

PS> 1..3 | Join-String -Separator ','
1,2,3

 

You can add a prefix and suffix to the final string:

PS> 1..3 | Join-String -OutputPrefix 'A' -OutputSuffix 'b' -Separator ','
A1,2,3b

 

You can use the property of objects on the pipeline as a source for the data:

PS> Get-ChildItem -Path C:\Scripts\Techniques\ | select -ExpandProperty Basename | Join-String -Separator ','
arrays,numbertechniques,stringtechniques

 

Quotes – single or double – can be added

PS> Get-ChildItem -Path C:\Scripts\Techniques\ | select -ExpandProperty Basename | Join-String -Separator ',' -SingleQuote
'arrays','numbertechniques','stringtechniques'

PS> Get-ChildItem -Path C:\Scripts\Techniques\ | select -ExpandProperty Basename | Join-String -Separator ',' -DoubleQuote
"arrays","numbertechniques","stringtechniques"

 

The current culture can also be use to influence the string. For instance dates:

PS> Get-Date

11 December 2018 16:25:43

PS> Get-Date | Join-String
12/11/2018 16:25:52

 

To me the string version of the date reads 12 November 2018 not 11 December 2018 so I need to use my culture

PS> Get-Date | Join-String -UseCulture
11/12/2018 16:26:54

 

And now it looks correct.

 

I suspect that Join-String will become one of those cmdlet that has many, many uses. For instance an easy way to create sequential file names:

PS> 1..5 | foreach {$_ | Join-String -OutputPrefix 'File' -OutputSuffix '.txt'}
File1.txt
File2.txt
File3.txt
File4.txt
File5.txt

Comments are closed.