101010
101010

Reputation: 15726

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

Given:

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

&echo $x $y

Used like so:

powershell test.ps1

Outputs:

> <blank line>

But then this goes wrong:

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

Outputs:

Hello,
my

I was expecting to see:

Hello, World! my friend

Upvotes: 27

Views: 73051

Answers (4)

Tobin
Tobin

Reputation: 2018

One can use a backtick ` to escape spaces:

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

Upvotes: 10

bubment
bubment

Reputation: 83

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

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

Upvotes: 8

Zach
Zach

Reputation: 63

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'"

Upvotes: 2

Nikolay K
Nikolay K

Reputation: 3850

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"
    

Upvotes: 47

Related Questions