PowerShell tricks – Build an array of strings without quotation marks

tree
This is one of the tricks I keep forgetting about and therefore document it here for myself but also in case someone else might find it useful.
In order to create an array of strings one usually does something like this:

$stringArray = "first", "second", "third", "fourth"

It involves quite some redundant characters in order to do a simple thing. This can be made easier using a simple function that is part of the excellent PowerShell Communicty Extensions. The QL (QL is short for Quote-List an idea borrowed from Perl) function has the following definition:

function ql {$args}
ql first second third fourth

Note that extraneous commas and quotation marks can be avoided using this approach. There is actually even a built-in cmdlet that can be used for the same purpose. Write-Output alias echo or write:

echo first second third fourth

If an element of the string array we’d like to create contains a space the element needs to be surrounded in quotes:

echo first second third fourth "with space"

As a bonus tip we can use a similar idea as for the ql function in order to create strings without having to limit them by quotation marks:

function qs {"$args"}
qs this is a long string without any quotes
#only gotcha is when using quotes (single or double) within the argument
#qs this does not' work
qs quotes require escaping using a `'backtick`' otherwise it will not work

shareThoughts


Photo Credit: bjimmy934 via Compfight cc

Advertisements

I'd love to hear what you think

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s