我什么时候需要在Powershell中使用引用?

时间:2012-07-11 14:02:14

标签: powershell

我什么时候需要在Powershell中用双引号括起字符串?我需要以下所有这些吗?

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

3 个答案:

答案 0 :(得分:4)

an explanation how to use apostrophes and quotes in PoSH。在您的示例中,您不需要它们,因为您不扩展变量或执行连接。

答案 1 :(得分:4)

在这种情况下,你不需要。

  • $sendemail希望已经是一个字符串,所以调用操作符&可以使用它(可能还有其他东西会被强制转换成字符串)。
  • 所有其他变量也应正确引用:

    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
    

如果要将包含特殊字符(例如shell运算符或空格)的文字字符串传递给程序,则需要引号,例如:

./echoargs 'some spaces and a | pipe'

如果你的所有参数都没有包含这样的东西,或者已经包含在字符串变量中,那么你就没有引号。

答案 2 :(得分:2)

到目前为止,所有答案都只提供完整问题答案的片段“你什么时候需要在PowerShell中引用(在需要时,你使用哪种类型)?”虽然有人愿意自然认为MSDN页面about_quoting_rules会有完整的答案,但事实并非如此。它主要涵盖字符串插值和字符串,但是地址是否或实际上是否需要引号。

PowerShell中的答案可能比其他语言更复杂,因为PowerShell提供了兼容脚本语言和shell语言的灵活性。 PowerShell旨在最大限度地减少shell的打字工作量,正如人们所期望的那样,在shell语言中,但与PowerShell脚本完全可互操作。

我实际上开始写一篇详细的答案来发布这里,但它一直在增长,直到它变成一篇文章长度的故事加上一个弹出的挂图(下面显示的片段),所有这些都发布在Simple-Talk.com上。请参阅When to Quote in PowerShell

enter image description here

相关问题