10

It appears that I can escape command line arguments using single or double quotes:

PS C:\> echo Hello World
Hello
World
PS C:\> echo 'Hello World'
Hello World
PS C:\> echo "Hello World"
Hello World

But there's still something I can't figure out, which is when you wish to run an executable from a directory that contains a space in it:

PS C:\> c:\program files\test.exe
The term 'c:\program' is not recognized as a cmdlet, function, operable program, or script file. Verify the term and try again.
At line:1 char:11
+ c:\program  <<<< files\test.exe
PS C:\> 'c:\program files\test.exe'
c:\program files\test.exe
PS C:\> "c:\program files\test.exe"
c:\program files\test.exe
PS C:\>

How do I get PowerShell to run the executable above?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Paul Hollingsworth
  • 13,124
  • 12
  • 51
  • 68
  • https://rkeithhill.wordpress.com/2007/11/24/effective-powershell-item-10-understanding-powershell-parsing-modes/ – chtenb Dec 10 '20 at 11:58

2 Answers2

20

Try putting an ampersand before the command. For example

& 'C:\Program Files\winscp\winscp.exe'
Dan Solovay
  • 3,134
  • 3
  • 26
  • 55
Rad
  • 8,336
  • 4
  • 46
  • 45
  • 1
    This is the more correct answer as it simply tells the parser to interpret the next token in command mode, though it looks like a string. – Nathan Hartley Nov 12 '10 at 16:19
11

Use this:

. "c:\program files\test.exe"

Actually an even better solution would be:

Invoke-Item "c:\program files\test.exe"

or using the alias:

ii "c:\program files\test.exe"

Using Invoke-Item means that the proper Windows file handler would be used. So for an EXE file it would run it. For a .doc file for instance, it would open it in Microsoft Word.

Here is one of the handiest PowerShell command lines around. Give it a try:

ii .
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
EBGreen
  • 36,735
  • 12
  • 65
  • 85
  • [Invoke-Item is evil](https://blogs.msdn.microsoft.com/powershell/2011/06/03/invoke-expression-considered-harmful/). – Peter Mortensen Sep 16 '18 at 23:12
  • Invoke-Expression certainly has security concerns associated with it's use but I'm not aware of issues with Invoke-Item. Could you elaborate? – EBGreen Sep 16 '18 at 23:15
  • You probably want to use `&` instead of `.` if you're trying to call an executable. The `.` call operator is really intended for including other PowerShell scripts in the current context. See [`Get-Help about_Operators`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-6). – Bacon Bits Sep 17 '18 at 03:17