2011-10-06 53 views
4

我有以下PowerShell腳本:如何將數組參數傳遞給powershell -file?

param(
    [Int32[]] $SomeInts = $null, 
    [String]$User = "SomeUser", 
    [String]$Password = "SomePassword" 
) 

New-Object PSObject -Property @{ 
    Integers = $SomeInts; 
    Login = $User; 
    Password = $Password; 
} | Format-List 

如果我執行.\ParameterTest.ps1 (1..10)我得到如下:

Password : SomePassword 
Login : SomeUser 
Integers : {1, 2, 3, 4...} 

但是,我沒有得到預期的結果,如果我在一個單獨的PowerShell中運行它像這樣的例子powershell -file .\ParameterTest.ps1 (1..10)。在這種情況下,我得到如下:

Password : 3 
Login : 2 
Integers : {1} 

我的問題是如何傳遞的陣列,或通過命令行其他複雜的數據類型?

回答

2

答案是使用powershell.exe -EncodedCommand並對base64進行參數編碼。對此的描述在PowerShell.exe Console Help technet頁面上。我已經壓縮了儀式的版本做成一個班輪這一點:

powershell.exe -EncodedCommand "$([Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes('.\ParameterTest.ps1 (1..10)')))" 
6

陣列(1..10)的各個元素被作爲參數傳遞給腳本。

另一種方法是做:

powershell -command {.\test.ps1 (1..10)} 

對於無論從PowerShell控制檯和CMD工作的版本:

powershell -command "&.\test.ps1 (1..10)" 
+0

這是簡單的,然後-EncodeCommand,並將從CMD.EXE作爲工作好。 –

相關問題