[英]Passing integer array as command line argument to powershell script
我有以下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
參數傳遞的任何數字作為一個數字進行處理,盡管我不確定為什么會發生這種情況,或者如何克服它。
問題是通過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]
,而逗號已被刪除,這意味着對於[int32]
,強制轉換1,2,3,4,5,6,10,11,12
太大,這會導致您的錯誤。
[int[]]'123456101112'
無法將值“ 123456101112”轉換為類型“ System.Int32 []”。 錯誤:“無法將值“ 123456101112”轉換為類型“ System.Int32”。錯誤:“對於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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.