2011-07-06 117 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))