Colonel Panic
Colonel Panic

Reputation: 137544

When do I need to use quotes in PowerShell?

When do I need to surround strings in double quotes in PowerShell? Do I need all of these below?

& "$sendemail" -f "$sender" -t "$recipient" -u "$subject" -o message-file="$logpath" -s "$emailserver" -o tls=no

Upvotes: 4

Views: 1313

Answers (3)

Akim
Akim

Reputation: 8669

There is an explanation how to use apostrophes and quotes in PowerShell. In your example you do not need them, as you do not expand variables, or perform concatenation.

Upvotes: 4

Michael Sorens
Michael Sorens

Reputation: 36698

All of the answers thus far give just fragments of the answer to the full question "When do you need quotes in PowerShell (and when needed, which kind do you use) ?" Though one would naturally think the MSDN page about_quoting_rules would have a full answer, it does not. It mostly covers just string interpolation and here strings but does not address whether or if you actually need quotes.

The answer is perhaps a bit more complicated in PowerShell than other languages because PowerShell provides the flexibility of being both a scripting language and a shell language. PowerShell was designed to minimize the typing effort for the shell, as one would expect in a shell language, but at the same time, to be fully interoperable with PowerShell scripts.

I actually started to write up a detailed answer to post here, but it grew and grew until it morphed into an article-length story plus a pop-out wallchart (fragment shown below), all published on Simple-Talk.com. See When to Quote in PowerShell.

enter image description here

Upvotes: 3

Joey
Joey

Reputation: 354406

In this case you need none.

  • $sendemail is hopefully already a string so the call operator & would work on it (maybe anything else would get coerced into a string anyway).
  • All other variables should be passed correctly-quoted as well:

    PS> $subject = 'subject string'
    PS> $recipient = 'recipient string'
    PS> $logpath = 'log path'
    PS> $emailserver = 'email server'
    PS> $recipient = 'recipient''s name'
    PS> $sender = 'sender''s name'
    PS> $sendemail = './echoargs.exe'
    PS> & $sendemail -f $sender -t $recipient -u $subject -o message-file=$logpath -s $emailserver -o tls=no
    arg 1: -f
    arg 2: sender's name
    arg 3: -t
    arg 4: recipient's name
    arg 5: -u
    arg 6: subject string
    arg 7: -o
    arg 8: message-file=log path
    arg 9: -s
    arg 10: email server
    arg 11: -o
    arg 12: tls=no
    

You would need quotes if you want to pass literal strings that contain special characters (e.g. shell operators or spaces) to a program, e.g.:

./echoargs 'some spaces and a | pipe'

If all your arguments either do not contain such things or are already contained in a string variable themselves you're good without quotes.

Upvotes: 5

Related Questions