gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:24:22 24 4
gpt4 key购买 nike

我有以下 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.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'

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.""


要继续使用 -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"

关于powershell - 将整数数组作为命令行参数传递给 powershell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45466376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com