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

4
我有以下 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命令行的解析器造成的。如果你从PowerShell提示符本身运行脚本(或函数),它应该按预期工作。 - Bill_Stewart
2
如果我没记错的话,-file 不支持参数数组,而 -command 更好用。powershell -Command "& .\test.ps1 -Ports 1,2,3,4,5,6,10,11,12" 这样做是否符合你的要求? - BenH
似乎在Linux / OSX上运行PoSh V 6.0.0beta。@BenH的提示在那里很好用。 - user6811411
1个回答

6
问题在于通过 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"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接