Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 
like image 670
101010 Avatar asked Feb 04 '15 00:02

101010


People also ask

How do you pass a space in PowerShell?

Use Single Quotes ' ' to Deal With Spaces in the Path in PowerShell.

How do I run a PowerShell script with spaces in path?

In case you want to run powershell.exe -File from the command line, you always have to set paths with spaces in double quotes (""). Also try using the Grave Accent Character (`) PowerShell uses the grave accent (`) character as its escape character.

Do spaces matter in PowerShell?

Spaces around special charactersWhite-space is (mostly) irrelevant to PowerShell, but its proper use is key to writing easily readable code.


1 Answers

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" 
like image 162
Nikolay K Avatar answered Oct 02 '22 16:10

Nikolay K