2013-10-24 228 views
6

編輯:我在這裏已經改變了代碼,以一個簡單的測試用例,而不是在那裏這個問題所帶來的全面實施。PowerShell腳本參數傳遞的數組

我試圖從另一個調用一個PowerShell腳本,但事情不工作了,我很期待。據我瞭解的東西,在「&」運營商應該擴大陣列分成不同的參數。這不會發生在我身上。

caller.ps1

$scriptfile = ".\callee.ps1" 
$scriptargs = @(
    "a", 
    "b", 
    "c" 
) 

& $scriptfile $scriptargs 

callee.ps1

Param (
    [string]$one, 
    [string]$two, 
    [string]$three 
) 

"Parameter one: $one" 
"Parameter two: $two" 
"Parameter three: $three" 

運行.\caller.ps1結果如下輸出:

Parameter one: a b c 
Parameter two: 
Parameter three: 

我認爲概率LEM我遇到的$scriptargs數組未展開,並作爲參數傳遞相當。我使用PowerShell的2

我怎樣才能得到caller.ps1與參數數組運行callee.ps1?

+0

我還應該在這裏注意到,我使用了PowerShell社區擴展的EchoArgs實用程序,並且參數顯示爲格式正確。 – Sam

+0

您將部署參數定義爲數組您是否嘗試將該字符串作爲表達式調用 – rerun

+0

我試圖將參數構建爲[本博客文章]上看到的數組(http://edgylogic.com/blog/powershell- and-external-commands-done-right /)標題下的「但是如果我想構建參數來傳遞我的腳本呢?」 – Sam

回答

9

當調用本機命令,像& $program $programargs通話將正確逃生的參數數組等等它被可執行文件正確解析。但是,對於PowerShell cmdlet,腳本或函數,不存在需要序列化/解析往返的外部編程,因此數組作爲單個值按原樣傳遞。

相反,可以使用splatting到陣列的元件(或散列表)傳遞到腳本:

& $scriptfile @scriptargs 

& $scriptfile @scriptargs@使值$scriptargs要被施加到的參數劇本。

+0

啊..濺濺..謝謝。 – sonjz

+2

請注意,splatting需要PowerShell 3.0或更高版本。 – Sam

+1

@Sam:MS至少說2.0 - > https://technet.microsoft.com/en-us/library/jj672955.aspx – Sebastian

1

你傳遞的變量作爲一個對象,你需要OT單獨通過他們。

這這裏工作:

$scriptfile = ".\callee.ps1" 
& $scriptfile a b c 

那麼,這是否:

$scriptfile = ".\callee.ps1" 
$scriptargs = @(
    "a", 
    "b", 
    "c" 
) 

& $scriptfile $scriptargs[0] $scriptargs[1] $scriptargs[2] 

如果你需要把它作爲一個單一的對象,像一個數組,那麼你可以有被叫腳本拆呢;具體代碼將取決於您傳遞的數據類型。

1

使用調用-表達的cmdlet:

Invoke-Expression ".\callee.ps1 $scriptargs" 

其結果是,你會得到:

PS > Invoke-Expression ".\callee.ps1 $scriptargs" 
Parameter one: a 
Parameter two: b 
Parameter three: c 
PS > 
+0

這可以工作,添加有利於您在設計時不需要知道參數將會是什麼(或其中有多少)。 – Sam

+3

Invoke-Expression引用的參數有很多痛苦的錯誤,也可能是安全漏洞(如果您不仔細檢查輸入)。 –

+0

我肯定更喜歡Emperor XLIIs解決方案。 – mzedeler