2011-07-06 213 views
22

使用powershell,可以使用'&'字符运行另一个应用程序并传入参数。动态生成命令行命令,然后使用powershell调用

一个简单的例子。

$notepad = 'notepad' 
$fileName = 'HelloWorld.txt' 

# This will open HelloWorld.txt 
& $notepad $fileName 

这很好。但是如果我想使用业务逻辑来动态生成命令字符串呢?使用相同的简单的例子:

$commandString = @('notepad', 'HelloWorld.txt') -join ' '; 
& $commandString 

我得到的错误:

The term 'notepad HelloWorld.txt' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

在我实际的例子我想动态添加或删除选项,最后的命令行字符串。有什么办法可以解决这个问题吗?

+0

是否在双引号(“”)帮助引用? – cristobalito

回答

25

两种方式做到这一点:

单独从参数的exe文件。做你的所有动态的东西来传递参数,但调用的exe按正常的变量之后举行的参数:

$argument= '"D:\spaced path\HelloWorld.txt"' 
$exe = 'notepad' 
&$exe $argument 

#or 
notepad $argument 

如果你有一个以上的说法,你应该让一个数组,如果这将是独立的从通话的EXE部分:

$arguments = '"D:\spaced path\HelloWorld.txt"','--switch1','--switch2' 
$exe = 'notepad' 
&$exe $arguments 

使用调用-表达。如果所有内容都必须位于字符串中,则可以像调用正常表达式那样调用该字符串。 Invoke-Expression也有iex的别名。

$exp = 'notepad "D:\spaced path\HelloWorld.txt"' 
Invoke-Expression $exp 

在任何一种情况下,参数和exe的内容都应引用和格式化,就好像它是直接写入命令行一样。

+1

还要注意,您需要自己在单个字符串中引用参数,以确保它们正确传递。 – Joey

+0

谢谢。这个问题给了我三种可用的选择,但是我最终使用了“将exe与参数分开”的路径。 –

+0

@Andrew:我大多数时候也使用这种方法,因为大多数语言在启动其他进程时都有类似的分离。 –

4

如果你想保住你的逻辑构建你的字符串:

$commandString = @('notepad', 'HelloWorld.txt') -join ' ' 

&([scriptblock]::create($commandstring))