【问题标题】:How to get powershell to output variable with quotes around it如何让powershell输出带有引号的变量
【发布时间】:2019-11-14 06:21:08
【问题描述】:

尽管使用“about_quoting_rules”查看了有关单引号和双引号的文档,但我似乎无法获得所需的输出。

一点背景故事:

我有一个 excel 文档,我正在使用 powershell 在每个条目上创建一个 foreach。这反过来又被用于生成 robocopy 命令以启动同步作业。

我的脚本中与此相关的部分如下:

Foreach($script in $roboSource)
{

    $StandardSwitches = "/copy:DAT /s /dcopy:DAT /V /L"
    $log = "/log:`"$($logPath)$($logFileName)`""                                                                                                #`
    $FileSource = "$($script.a)"
    $FileDestination = "$($script.a)"

    $RoboArgs = "I:\" + $FileSource + " " + "Z:\" + $FileDestination + " " + $StandardSwitches + " " + $log
}

所以,现在,$RoboArgs 输出:

I:\XXXXX\XXXXX\X\XXXXXXX\XXXXX\XXXX Z:\XXXXX\XXXXX\X\XXXXXXX\XXXXX\XXXX /copy:DAT /s /dcopy:DAT /V /L /log:"C:\XXXXX\XXXXX\X\XXXXXXX\XXXXX\XXXX"

我需要 $RoboArgs 输出的是:

"I:\XXXXX\XXXXX\X\XXXXXXX\XXXXX\XXXX" "Z:\XXXXX\XXXXX\X\XXXXXXX\XXXXX\XXXX" /copy:DAT /s /dcopy:DAT /V /L /log:"C:\XXXXX\XXXXX\X\XXXXXXX\XXXXX\XXXX"

我已经尝试将反引号添加到字符串中,并将字符串和变量封装在一起:

$RoboArgs = `""I:\" + $FileSource`"" + " " + "Z:\" + $FileDestination + " " + $StandardSwitches + " " + $log

但无论我尝试什么,都不会产生我正在寻找的输出。任何朝着正确方向的推动都会非常有帮助和感激!

【问题讨论】:

    标签: powershell powershell-4.0


    【解决方案1】:

    在 Powershell 中 ` 后跟引号有效,如其他语言中的 '\'

    例如:

    "`"toto`""
    

    打印

    "toto"
    

    【讨论】:

      【解决方案2】:

      我建议使用PowerShell的string-formatting operator-f

      $RoboArgs = '"I:\{0}" "Z:\{1}" {2} {3} {4}' -f 
                    $FileSource, $FileDestination, $StandardSwitches, $log
      
      • 使用'...'(单引号)作为分隔符允许您按原样嵌入" 实例。

      • {0} 是第一个 RHS 操作数的占位符,{1} 是第二个操作数,依此类推。

      【讨论】:

        【解决方案3】:

        尝试用单引号分隔您的字符串。里面的任何双引号都将保留在结果字符串中。

        例子:

        $stringWithQuotes = '"' + (pwd) + '"'
        

        如果你想在你的字符串中使用单引号,你也可以反过来做:

        $stringWithQuotes = "'" + (pwd) + "'"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-02-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-09-02
          • 1970-01-01
          • 2011-04-05
          • 2011-02-10
          相关资源
          最近更新 更多