Monday, 6 October 2014

PowerShell: Array to a Comma Separated String in One LIne

Today I got asked how to take the output of a list of servers, append the domain name to each server, and then output the list as a single comma separated string.

After trying to achieve it with one single short line of PowerShell, I settled on three lines of code. I then got chastised by My Crazy Brazilian Colleague (MCBC) for always writing too many one liners in my scripts! Apparently too many condensed, piped one liners, make a PowerShell script hard to read. After all, a PowerShell script isn't meant to be a minimised JavaScript file!

Now while I agree with MCBC in principal, failing to pipe (and append text to) all the strings in the array, into a single comma seperated string object, bugged me for the rest of the day!

Determined to prove the point, I came up with this. My array to string one liner, that goes against readability!

First, my formula!

$a | %{$v += ($(if($v){", "}) + $_ + $t)}

That definitely isn't readable, so here's an example (the single line of code, obviously being the middle line!)

#Define an array of text values            
$a = @("orange","apple","kiwi","banana")
#One line of PowerShell to output the values into a single comma separated string, appending "'s are delicious" to each string            
$a | %{$v += ($(if($v){", "}) + $_ + "'s are delicious")}
#Print the value            
$v



In our scenario today, we took a list of servers from a SharePoint farm, and then piped the server names into some other command (which I don't care to recall!). Had I thought of this during the day, instead of on the train during the commute home, the PowerShell would have looked this:

#Get the list of servers from SharePoint            
$sl = (Get-SPFarm).Servers | Select Name            
#For each server, add the domain name            
$sl | %{$v += ($(if($v){","}) + $_.Name + "." + $env:USERDNSDOMAIN)}            
#Print the array            
$v



And finally, for those unclear on what is happening, here's a pict-o-gram!



Sorry MCBC, I couldn't resist!