Powershell .Split() and -Join
Last post I showed how to use .Split() to separate Path and CLASSPATH variables into an easily readable list of paths ( $env:Path.Split(“;”) or $env:CLASSPATH.Split(“;”) ). Of course .Split() can be used to split on other characters like “,”, “ “ (space) or “`t” (tab).
But what if you have a list and want to turn it into one line of delimiter-separated values? Consider the following as the contents of flatfile.txt:
One
Two
Red
Blue
Try this:
(Get-Content ".\flatfile.txt") -Join ","
# One,Two,Red,Blue
Or if you want it in a variable first:
$list = Get-Content ".\flatfile.txt"
$commaList = $list -Join ","
Write-Host $commaList
# One,Two,Red,Blue
$spaceList = $list -Join " "
Write-Host $spaceList
# One Two Red Blue
$tabList = $list -Join "`t"
# ` this comment is to fix a syntax highlighting issue on my site
Write-Host $tabList
# One Two Red Blue
$sillyList = $list -Join " <-- Look a value there, and another one here -->"
Write-Host $sillyList
# One <-- Look a value there, and another one here --> Two <-- Look a value there, and another one here --> Red <-- Look a value there, and another one here --> Blue