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

Jar*_*red 4 powershell

我有以下 powershell 脚本:

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

Write-Host $Ports.count

foreach($port in $Ports) {
 Write-Host `n$port
}
Run Code Online (Sandbox Code Playgroud)

当我运行脚本时$ powershell -File ./test1.ps1 -Ports 1,2,3,4它可以工作(但不符合预期):

1

1234
Run Code Online (Sandbox Code Playgroud)

当我尝试使用更大的数字 时,$ 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
Run Code Online (Sandbox Code Playgroud)

看起来 powershell 正在尝试将通过Ports参数传递的任何数字作为单个数字进行处理,尽管我不确定为什么会发生这种情况,或者如何绕过它。

Ben*_*enH 6

问题是传递的参数powershell.exe -File是[string].

所以对于你的第一个例子,

powershell -File ./test1.ps1 -Ports 1,2,3,4
Run Code Online (Sandbox Code Playgroud)

$Ports被传递为[string]'1,2,3,4',然后尝试强制转换为[int[]]。您可以通过以下方式查看会发生什么:

[int[]]'1,2,3,4'
1234
Run Code Online (Sandbox Code Playgroud)

知道它只是一个[int32]删除了逗号的常规值意味着转换1,2,3,4,5,6,10,11,12太大,[int32]这会导致您的错误。

[int[]]'123456101112'
Run Code Online (Sandbox Code Playgroud)

无法将值“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
}
Run Code Online (Sandbox Code Playgroud)

但幸运的是,这是不必要的,因为还有powershell.exe -command. 您可以调用该脚本并使用PowerShell引擎来解析参数。这会正确地将Port参数视为数组。

powershell -Command "& .\test.ps1 -Ports 1,2,3,4,5,6,10,11,12"
Run Code Online (Sandbox Code Playgroud)