我还没有太多的 PowerShell 经验,正在尝试自学。
我正在尝试为更大的项目制作一些概念验证代码。这里的主要目标是使用函数动态地创建元素并将其添加到数组中。
这是我的代码:
$testArray = @()
function addToArray($Item1)
{
$testArray += $Item1
"###"
}
$tempArray = "123", "321", "453"
$foldertest = "testFolder"
foreach($item in $tempArray)
{
addToArray $item
}
"###"
每次函数完成时,数组都会变空。 请记住,我的大部分编程经验来自 Java、PHP、一些 C 和 C++,仅举几例,如果我在 PHP 中执行此操作(当然调整语言语法),那么效果会很好。
$testArray = [System.Collections.ArrayList]@()
$tempArray = "123", "321", "453"
foreach($item in $tempArray)
{
$arrayID = $testArray.Add($item)
}
问题是范围之一;在你的 addToArray 函数中将这一行更改为:
$script:testArray += $Item1
...存储到您期望的数组变量中。
注意:如果您想要拥有动态(非固定)数量的项目,更精确的解决方案可能是使用
List
:
$testArray = New-Object System.Collections.Generic.List[System.Object]
$tempArray = "123", "321", "453"
foreach($item in $tempArray)
{
$testArray.Add($item)
}
注意:在这种情况下,您可以从 .Net 获得列表的强大功能,因此您可以轻松应用 linq、合并、拆分以及执行您在 .Net 中使用列表
所做的任何操作不要在每次循环迭代中重新创建数组(这基本上是每次添加数组时发生的情况),而是将循环的结果分配给变量:
$testArray = foreach($item in $tempArray)
{
addToArray $item
}
如果你想在数组的开头添加一个项目(作为索引 0),这可能会起作用,就像 PHP 上的 array_unshift($array, $item) 一样:
$tempArray = "123", "321", "453"
$foldertest = "testFolder"
$tempArray = @($foldertest) + $tempArray
这给出:
PS D:\users\user1 emp> $temparray 测试文件夹 123 321 第453章