【问题标题】:How do I pass in a string with spaces into PowerShell?如何将带有空格的字符串传递到 PowerShell?
【发布时间】:2015-02-04 00:06:42
【问题描述】:

给定:

# test1.ps1
param(
    $x = "",
    $y = ""
)

&echo $x $y

这样使用:

powershell test.ps1

输出:

> <blank line>

但是接下来就出错了:

test.ps1 -x "Hello, World!" -y "my friend"

输出:

Hello,
my

我期待看到:

Hello, World! my friend

【问题讨论】:

  • 这适用于我的 powershell 提示符,但从 cmd.exe 失败。这使得这是一个 cmd.exe 限制。在那里使用单引号似乎可以工作......这很奇怪,因为我认为 cmd.exe 根本没有处理单引号。
  • 那么这是一个powershell问题还是一个cmd.exe问题?看来您已经回答了自己的问题?

标签: powershell


【解决方案1】:

嗯,这是一个cmd.exe 问题,但是有一些方法可以解决它。

  1. 使用单引号

    powershell test.ps1 -x 'hello world' -y 'my friend'
    
  2. 使用-file 参数

    powershell -file test.ps1 -x "hello world" -y "my friend"
    
  3. 使用以下内容创建.bat 包装器

    @rem test.bat
    @powershell -file test.ps1 %1 %2 %3 %4
    

    然后调用它:

    test.bat -x "hello world" -y "my friend"
    

【讨论】:

  • 我在从 Windows 中的计划任务运行 PowerShell 脚本时遇到了这个问题。脚本的一个参数用于构建路径并在其中有一个空格,脚本失败了,因为它删除了空格之后的所有内容。添加 -File 参数解决了这个问题。
  • -File- did not work, I solved it by directly quoting the arg %1` 并转义给出的报价:\"%1\"。然后我可以毫无问题地使用$arg(路径不再在第一个空格处中断)
  • -File 帮助处理文件名包含空格的脚本。但是,它会影响 PowerShell 解析剩余命令行的方式。 - 的参数会产生一个奇怪的错误(可能是 PowerShell 错误),-: 也是如此。以前带括号的参数必须放在单引号中;现在必须删除那些,否则它们将传递给脚本。 PowerShell 5.1。
【解决方案2】:

可以使用反引号`来转义空格:

PS & C:\Program` Files\\....

【讨论】:

  • 或者如上所述转义命令行中的引号,例如powershell somefile \"arg with space\"
【解决方案3】:

在我的例子中,一个可能的解决方案是嵌套单引号和双引号。

test.ps1 -x '"Hello, World!"' -y '"my friend"'

【讨论】:

  • 我试图运行具有多个配置文件(如 profile1,profile2)的 java 应用程序,而您的解决方案是唯一对我有用的解决方案。
【解决方案4】:

我遇到了类似的问题,但在我的情况下,我试图运行一个 cmdlet,并且调用是在 Cake 脚本中进行的。在这种情况下,单引号和 -file 参数不起作用:

powershell Get-AuthenticodeSignature 'filename with spaces.dll'

产生的错误:Get-AuthenticodeSignature : A positional parameter cannot be found that accepts argument 'with'.

如果可能,我想避免使用批处理文件。

解决方案

起作用的是使用带有 /S 的 cmd 包装器来解开外部引号:

cmd /S /C "powershell Get-AuthenticodeSignature 'filename with spaces.dll'"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多