【发布时间】:2021-03-03 03:17:08
【问题描述】:
认为我在这里和其他地方已经阅读了足够多的示例。我仍然无法在 Power Shell 中创建数组。
我希望通过该代码从数组中创建对值的切片。
$values = @('hello','world','bonjour','moon','ola','mars')
function slice_array {
param (
[String[]]$Items
)
[int16] $size = 2
$pair = [string[]]::new($size) # size is 2
$returns = [System.Collections.ArrayList]@()
[int16] $_i = 0
foreach($item in $Items){
$pair[$_i] = $Item
$_i++;
if($_i -gt $size - 1){
$_i = 0
[void]$returns.Add($pair)
}
}
return $returns
}
slice_array($values)
输出是
ola
mars
ola
mars
ola
mars
希望
'hello','world'
'bonjour','moon'
'ola','mars'
是否可以将该数组切片为长度为 2 的数组?
任何解释为什么它不能按预期工作? 代码应该怎么改?
感谢您提供正确理解 PowerShell 中的数组的任何提示!
【问题讨论】:
-
顺便说一句:必须调用 PowerShell 函数、cmdlet、脚本和外部程序方法 -
foo('arg1', 'arg2')。如果您使用,分隔参数,您将构造一个命令将其视为单个参数 的数组。为防止意外使用方法语法,请使用Set-StrictMode -Version 2或更高版本,但请注意其其他影响。请参阅this answer 了解更多信息。
标签: powershell