0

我对 Powershell 很陌生,并且正在从事一个带有功能的小项目。我想要做的是创建一个带有 2 个参数的函数。第一个参数 ($Item1) 决定数组的大小,第二个参数 ($Item2) 决定索引的值。

因此,如果我写: $addToArray 10 5 我需要该函数来创建一个包含 10 个索引且每个索引值为 5 的数组。第二个参数也必须将“文本”作为一个值。

到目前为止,这是我的代码。

$testArray = @();

$indexSize = 0;

function addToArray($Item1, $Item2)

{

while ($indexSize -ne $Item1)

{

        $indexSize ++;    
    }

    Write-host "###";

    while ($Item2 -ne $indexSize)
    {
        $script:testArray += $Item2;
        $Item2 ++;
    }
}

任何帮助表示赞赏。

亲切的问候丹尼斯伯恩森

4

3 回答 3

1

有很多方法可以做到这一点,这里有一个简单的(长版):

function addToArray($Item1, $Item2)
{
    $arr = New-Object Array[] $Item1

    for($i=0; $i -lt $arr.length; $i++)
    {
        $arr[$i]=$Item2
    }

    $arr
}

addToArray 10 5 
于 2013-11-09T10:40:17.610 回答
1

这是另一种可能性:

function addToArray($Item1, $Item2)
 {
   @($Item2) * $Item1
 }
于 2013-11-09T11:27:45.103 回答
1

还有一个。

function addToArray($Item1, $Item2) {
    #Counts from 1 to your $item1 number, and for each time it outputs the $item2 value.
    (1..$Item1) | ForEach-Object {
        $Item2
    }
}

#Create array with 3 elements, all with value 2 and catch/save it in the $arr variable
$arr = addToArray 3 2

#Testing it (values under $arr is output)
$arr
2
2
2
于 2013-11-09T13:59:51.017 回答