如何在PowerShell上转义命令行参数?

如何在PowerShell上转义命令行参数?,powershell,Powershell,似乎可以使用单引号或双引号转义命令行参数: PS C:\> echo Hello World Hello World PS C:\> echo 'Hello World' Hello World PS C:\> echo "Hello World" Hello World 但还有一件事我想不通,那就是当您希望从包含空格的目录中运行可执行文件时: PS C:\> c:\program files\test.exe The term 'c:\program' is not

似乎可以使用单引号或双引号转义命令行参数:

PS C:\> echo Hello World
Hello
World
PS C:\> echo 'Hello World'
Hello World
PS C:\> echo "Hello World"
Hello World
但还有一件事我想不通,那就是当您希望从包含空格的目录中运行可执行文件时:

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:\>
PS C:\>C:\program files\test.exe
术语“c:\program”不能识别为cmdlet、函数、可操作程序或脚本文件。请验证术语,然后重试。
第1行字符:11
+c:\程序
如何让PowerShell运行上述可执行文件?

使用以下方法:

. "c:\program files\test.exe"
实际上,更好的解决方案是:

Invoke-Item "c:\program files\test.exe"
或使用别名:

ii "c:\program files\test.exe"
使用Invoke项意味着将使用正确的Windows文件处理程序。因此,对于EXE文件,它将运行它。例如,对于.doc文件,它将在Microsoft Word中打开它

下面是最方便的PowerShell命令行之一。试一试:

ii .

试着在命令前加一个符号。比如说

& 'C:\Program Files\winscp\winscp.exe'

这是一个更正确的答案,因为它只是告诉解析器在命令模式下解释下一个标记,尽管它看起来像一个字符串。.Invoke表达式肯定与它的使用相关联的安全问题,但我不知道Invoke Item有什么问题。你能详细说明一下吗?如果你试图调用一个可执行文件,你可能想使用
&
而不是
调用操作符实际上用于在当前上下文中包含其他PowerShell脚本。看见