How do I pass in a string with spaces into PowerShell?

前端 未结 4 1628
庸人自扰
庸人自扰 2020-12-18 21:38

Given:

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

&echo $x $y

Used like so:

powershell test.ps1
相关标签:
4条回答
  • 2020-12-18 22:06

    Randomly found this today; you can use a backtick ` to escape spaces:

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

    Just in case anyone stumbles onto this again

    0 讨论(0)
  • 2020-12-18 22:20

    Well, this is a cmd.exe problem, but there are some ways to solve it.

    1. Use single quotes

      powershell test.ps1 -x 'hello world' -y 'my friend'
      
    2. Use the -file argument

      powershell -file test.ps1 -x "hello world" -y "my friend"
      
    3. Create a .bat wrapper with the following content

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

      And then call it:

      test.bat -x "hello world" -y "my friend"
      
    0 讨论(0)
  • 2020-12-18 22:21

    I had a similar problem but in my case I was trying to run a cmdlet, and the call was being made within a Cake script. In this case the single quotes and -file argument did not work:

    powershell Get-AuthenticodeSignature 'filename with spaces.dll'
    

    Resulting error: Get-AuthenticodeSignature : A positional parameter cannot be found that accepts argument 'with'.

    I wanted to avoid the batch file if possible.

    Solution

    What did work was to use a cmd wrapper with /S to unwrap outer quotes:

    cmd /S /C "powershell Get-AuthenticodeSignature 'filename with spaces.dll'"
    
    0 讨论(0)
  • 2020-12-18 22:27

    A possible solution was in my case to nest the single and the double quotes.

    test.ps1 -x '"Hello, World!"' -y '"my friend"'
    
    0 讨论(0)
提交回复
热议问题