Reputation: 8610
I have the following powershell script:
param (
[Parameter(Mandatory=$true)][int[]]$Ports
)
Write-Host $Ports.count
foreach($port in $Ports) {
Write-Host `n$port
}
When I run the script with $ powershell -File ./test1.ps1 -Ports 1,2,3,4
it works (but not as expected):
1
1234
When I try to use larger numbers, $ powershell -File .\test.ps1 -Ports 1,2,3,4,5,6,10,11,12
, the script breaks entirely:
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
It seems like powershell is trying to process any numbers passed via the Ports
param as a single number, though I'm not sure why this is happening, or how to get past it.
Upvotes: 4
Views: 5547
Reputation: 10044
The issue is that a parameter passed through powershell.exe -File
is a [string]
.
So for your first example,
powershell -File ./test1.ps1 -Ports 1,2,3,4
$Ports
is passed as [string]'1,2,3,4'
which then attempts to get cast to [int[]]
. You can see what happens with:
[int[]]'1,2,3,4'
1234
Knowing that it will be an just a regular [int32]
with the comma's removed means that casting 1,2,3,4,5,6,10,11,12
will be too large for [int32]
which causes your error.
[int[]]'123456101112'
Cannot convert value "123456101112" to type "System.Int32[]". Error: "Cannot convert value "123456101112" to type "System.Int32". Error: "Value was either too large or too small for an Int32.""
To continue using -file
you could parse the string yourself by splitting on commas.
param (
[Parameter(Mandatory=$true)]
$Ports
)
$PortIntArray = [int[]]($Ports -split ',')
$PortIntArray.count
foreach ($port in $PortIntArray ) {
Write-Host `n$port
}
But luckily that is unnecessary because there is also powershell.exe -command
. You can call the script and use the PowerShell engine to parse the arguments. This would correctly see the Port
parameter as an array.
powershell -Command "& .\test.ps1 -Ports 1,2,3,4,5,6,10,11,12"
Upvotes: 6