我有以下 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-file
不支持参数数组,而-command
更好用。powershell -Command "& .\test.ps1 -Ports 1,2,3,4,5,6,10,11,12"
这样做是否符合你的要求? - BenH