【问题标题】:Passing double quotes through PowerShell + WinRM通过 PowerShell + WinRM 传递双引号
【发布时间】:2014-01-16 18:55:04
【问题描述】:

我正在使用这个code 在服务器上执行远程代码(MSI 安装)。通过脚本传递双引号是行不通的。我尝试了下面给出的两种变体(#3 和 #4)以及输出。

输入#1(测试命令中双引号的简单案例)

powershell.exe -inputformat none -File client.ps1 -target 1.2.3.4 -port 5985 -password "pass" -username "user" -command "echo hello"

输出(作品)

hello

输入 #2(可以理解,这行不通)

powershell.exe -inputformat none -File client.ps1 -target 1.2.3.4 -port 5985 -password "pass" -username "user" -command "echo hello world"

输出

hello
world

输入 #3

powershell.exe -inputformat none -File client.ps1 -target 1.2.3.4 -port 5985 -password "pass" -username "user" -command "echo `"hello world`""

输出(另一个词怎么了?)

hello

输入 #4

powershell.exe -inputformat none -File client.ps1 -target 1.2.3.4 -port 5985 -password "pass" -username "user" -command @'
>> echo "hello world"
>> '@
>>

输出(同样,缺少第二个单词)

hello

如果回显有效,我应该能够在我正在做的基于运行空间的使用中合并对 MSI 命令的更改。


如果我使用以下设置,MSI 设置工作正常。注意单引号。

msiexec /qn /i 'C:\setups\My Software.msi'

但是,我需要传递公共属性,而 MSI 不喜欢其中的单引号。尝试运行以下命令会打开 MSI 参数对话框。

msiexec /qn /i 'C:\setups\My Software.msi' MYPROP='My Value'

从服务器上的本地命令提示符运行它可以正常工作。

msiexec /qn /i "C:\setups\My Software.msi" MYPROP="My Value"

【问题讨论】:

    标签: powershell windows-installer winrm runspace


    【解决方案1】:

    如果你从 cmd.exe 调用这个,你必须根据 CMD 的规则转义双引号。

    powershell.exe -command "echo \"hello world\""
    

    输出

    hello world
    

    就个人而言,我建议尽可能避免从命令行传入参数。也许您可以将参数值存储在一个文件中(例如,序列化的 XML、JSON),然后让 PowerShell 脚本读取该文件?

    更好的是,我建议通过Start-Process cmdlet 对进程(例如msiexec.exe)进行任何处理。这样,您可以在变量中建立-ArgumentList 参数的值,然后保证它会完全按照您想要的方式传递,此外,您将不受@ 的引用规则的限制987654327@.

    考虑以下几点:

    $ArgumentList = '/package "c:\setups\My Software.msi" /passive /norestart /l*v "{0}\temp\Install My Software.log" MYPROP="My Value With Spaces"' -f $env:windir;
    Start-Process -FilePath msiexec.exe -ArgumentList $ArgumentList;
    

    【讨论】:

    • 成功了。我修改了 Invoke-Command 的 ScriptBlock 以使用上述内容。在传递到 Runspace 之前,我为我在运行时替换的动态项目保留了占位符。
    • 谢谢,+1。您的回答帮助我解决了我的相关问题---> stackoverflow.com/questions/42065666/…
    【解决方案2】:

    或者您可以将命令编码为 base64 字符串,以避免意外解释任何特殊字符,例如封装的双引号。

    powershell.exe -EncodedCommand "ZQBjAGgAbwAgACIAaABlAGwAbABvACAAdwBvAHIAbABkACIA"

    结果

    hello world
    

    ZQBjAGgAbwAgACIAaABlAGwAbABvACAAdwBvAHIAbABkACIA .... 是这个的 base64 表示。看看我如何不需要逃避任何事情。

    echo "hello world"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-22
      • 2018-04-14
      • 2019-05-02
      • 1970-01-01
      • 2021-09-14
      • 2019-07-25
      • 1970-01-01
      • 2020-01-07
      相关资源
      最近更新 更多