导航

[转]动态执行PowerShell命令

Posted on 2014-03-10 13:10  FryFish  阅读(430)  评论(0)    收藏  举报

Two ways to do that:

I. Separate the exe from the arguments

Do all your dynamic stuff for the arguments, but call the exe as normal with the variable holding the arguments afterward:

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

#or
notepad $argument

If you have more than one argument, you should make it an array if it will be separate from the exe part of the call:

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

2. Use Invoke-Expression

If everything must be in a string, you can invoke the string as if it were a normal expression. Invoke-Expression also has the alias of iex.

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

In either case, the contents of the arguments and of the exe should be quoted and formatted appropriately as if it were being written straight on the commandline.

转自:http://stackoverflow.com/questions/6604089/dynamically-generate-command-line-command-then-invoke-using-powershell