2017-08-02 190 views
2

我有以下PowerShell腳本:傳遞整數數組作爲命令行參數PowerShell腳本

param (
    [Parameter(Mandatory=$true)][int[]]$Ports 
) 

Write-Host $Ports.count 

foreach($port in $Ports) { 
Write-Host `n$port 
} 

當我$ powershell -File ./test1.ps1 -Ports 1,2,3,4運行該腳本,它的工作原理(但並不如預期):

1 

1234 

當我嘗試使用較大的數字時,$ powershell -File .\test.ps1 -Ports 1,2,3,4,5,6,10,11,12,腳本完全中斷:

test.ps1 : Cannot process argument transformation on parameter 'Ports'. Cannot convert value "1,2,3,4,5,6,10,11,12" to type "System.Int32[]". Error: "Cannot convert value "1,2,3,4,5,6,10,11,12" to type "System.Int32". Error: "Input 
string was not in a correct format."" 
    + CategoryInfo   : InvalidData: (:) [test.ps1], ParentContainsErrorRecordException 
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,test.ps1 

它看起來像powershell試圖處理通過Ports param作爲單個數字傳遞的任何數字,但我不知道爲什麼會發生這種情況,或者如何通過它。

+0

這很可能是由於解析你的'powershell'命令行。如果從PowerShell提示本身運行腳本(或函數),它應該按預期工作。 –

+2

如果我沒有記錯,'-file'不喜歡參數數組。 「命令」效果更好。 'powershell -Command「&。\ test.ps1 - 端口1,2,3,4,5,6,10,11,12」'按照你想要的方式工作嗎? – BenH

+0

似乎在Linux/OSX上運行PoSh V 6.0.0beta @BenHs提示在那裏工作很好。 – LotPings

回答

2

問題是通過powershell.exe -File傳遞的參數是[string]

因此,對於你的第一個例子,

powershell -File ./test1.ps1 -Ports 1,2,3,4 

$Ports[string]'1,2,3,4',然後嘗試獲取投地[int[]]傳遞。你可以看到發生了什麼:

[int[]]'1,2,3,4' 
1234 

知道,這將是一個只是一個普通的[int32]用逗號刪除意味着鑄造1,2,3,4,5,6,10,11,12將是[int32]這會導致你的錯誤太大。

[int[]]'123456101112' 

Cannot convert value "123456101112" to type "System.Int32[]". Error: "Cannot convert value "123456101112" to type "System.Int32". Error: "Value was either too large or too small for an Int32.""


要繼續使用-file你可以通過拆分的逗號解析自己的字符串。

param (
    [Parameter(Mandatory=$true)] 
    $Ports 
) 

$PortIntArray = [int[]]($Ports -split ',') 

$PortIntArray.count  

foreach ($port in $PortIntArray) { 
    Write-Host `n$port 
} 

但幸運的是這是不必要的,因爲也有powershell.exe -command。您可以調用腳本並使用PowerShell引擎來解析參數。這將正確地將Port參數看作一個數組。

powershell -Command "& .\test.ps1 -Ports 1,2,3,4,5,6,10,11,12"