Sometimes it’s the little things that can make life easier. Here’s one of them. We know that PowerShell treats comma separated items as an array:
PS C:\> $a=”a”,1,”b”,”jeff”,4
PS C:\> $a
a
1
b
jeff
4
PS C:\>
But what if you want back in its original comma delimited list? Or suppose you wanted to create a comma delimited line of all running services? Export-CSV isn’t really going to help in these situations. I came up with function called Out-CSV.
Function out-csv {
BEGIN {
#probably not necessary
[string]$csv=""
}
PROCESS {
#force each item to be a string and trim any spaces
$item=($_ | out-string).Trim()
if ($csv) {
$csv+="," + $item
}
else {
#first item in the string
$csv=$item
}
}
END {
#send the comma separated string into the pipeline
write $csv
}
}
The function uses the Begin/Process/End script blocks so it can accept pipelined input. The function is pretty simple. It merely concatenates each item into a comma delimited string.
PS C:\> $a | out-csv
a,1,b,jeff,4
Out-CSV needs strings so to work with other cmdlets takes a little extra work.
PS C:\> get-service | where {$_.status -eq “running”} | foreach {$_.name} | out-csv
This will create comma separated list of all running services.Granted, the need for such a list may be limited but if you need it, now you have a tool to get it.
Download the script file here.
1 comment on “Out-CSV”
Comments are closed.