如何在PowerShell中避免命令行参数?

10

看起来我可以使用单引号或双引号来转义命令行参数:

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:\>

如何让PowerShell运行上面的可执行文件?


https://rkeithhill.wordpress.com/2007/11/24/effective-powershell-item-10-understanding-powershell-parsing-modes/ - chtenb
2个回答

20

尝试在命令之前加上一个&符号。例如:

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

1
这是更正确的答案,因为它告诉解析器在命令模式下解释下一个标记,尽管它看起来像一个字符串。 - Nathan Hartley

11

使用这个:

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

实际上,更好的解决方案是:

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

使用Invoke-Item命令可以确保使用适当的Windows文件处理程序。因此,对于一个EXE文件,它会运行它。例如对于一个.doc文件,它会在Microsoft Word中打开它。

这里有一个最方便的PowerShell命令行之一。试试看:

ii .

Invoke-Item 是邪恶的 - Peter Mortensen
Invoke-Expression的确存在与安全相关的问题,但我不知道使用Invoke-Item会有什么问题。你能详细说明一下吗? - EBGreen
如果你想调用一个可执行文件,那么你可能想使用 & 而不是 .. 调用运算符实际上是为了在当前上下文中包含其他 PowerShell 脚本。请参阅 Get-Help about_Operators - Bacon Bits

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接