4

#PSTip A quick list of strings

When you need to create a collection of strings and operate on each of them you’d go with something like:

'one','two','three','four','five' | ForEach-Object { $_ }

As you can see, and your fingers probably feel, those strings needs to be quoted and comma delimited before they can be written to the pipeline. One way to avoid this is to create a helper function (coming from Perl), Quote-List (or ql for short):

PS> function ql { $args }
PS> ql one two three four five | ForEach-Object { $_ }

The function takes a list of unquoted arguments and returns a collection of strings. That’s cool but it requires you to create the ql function or make sure it’s present on all systems you intend to use it on. Actually, there’s a better, built-in way, of doing this without having to create helper function. The answer is the Write-Output cmdlet. In the following example, I’m using Write-Output’s ‘echo’ alias:

PS> echo one two three four five | ForEach-Object { $_ }

If you can’t live without commas, this is also valid:

PS> echo one,two,three,four,five | ForEach-Object { $_ }
Filed in: Columns, Tips and Tricks Tags: , , , ,

4 Responses to "#PSTip A quick list of strings"

  1. There seems to be no Write-Object cmdlet in PowerShell. ‘echo’ is an alias for Write-Output.

  2. michaelds says:

    BUT, actually, you do not need to use foreach-object. Just write: echo a,b,c. It works!

Leave a Reply

Submit Comment

© 2016 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: