将整数数组作为命令行参数传递给powershell脚本

时间:2017-08-02 16:34:25

标签: 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传递的任何数字作为单个数字,但我不确定为什么会发生这种情况,或者如何通过它。

1 个答案:

答案 0 :(得分:3)

问题是通过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'
  

无法将值“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"
相关问题