1

我有一个简单的问题。我想将命令分配给变量并使用额外的参数执行它,例如:

C:\test.exe /q /v

但是当我这样做时:

$path=C:\test.exe
$path /q /v

它不起作用..有什么想法吗?

4

2 回答 2

3

最规范的方法是在包含命令“名称”的变量上使用调用运算符,例如:

& $path /q /v

当命令的路径(即本机 exe)包含空格时,这实际上是必需的。

于 2013-06-05T15:31:57.277 回答
2

Command as string:

With Invoke-Expression cmdlet you execute an arbitrary string as a piece of code. It takes the string, compiles it, and executes it.

So you do:

$path='C:\test.exe';
Invoke-Expression "$path /q /v";

As a side note: When you do $path=C:\test.exe without the quotes, you are actually assigning the STDOUT of test.exe to the variable $path. You have to make clear to PowerShell that it is actually a string you wish to execute later.


Command as script object:

If you are concerned with performance, you could also try converting your command to a compiled scriptblock, and execute it with the & call operator.

$path='C:\test.exe';
$cmd = [scriptblock]::Create("$path /q /v");
& $cmd;
于 2013-06-05T13:19:23.573 回答