2013-11-09 41 views
0

我对Powershell颇为陌生,并且正在处理一个带有函数的小项目。 我想要做的是创建一个函数,需要2个参数。 第一个参数($ Item1)决定了数组的大小,第二个参数($ Item2)决定了索引的值。通过输入创建数组的Powershell函数

所以,如果我写︰$ 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 ++; 
    } 
} 

任何帮助表示赞赏。

亲切的问候 丹尼斯Berntsson

回答

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 
+0

感谢您发布此信息,它可以帮助我更好地了解Powershell。 – Azely

1

这里的另一种可能性:

function addToArray($Item1, $Item2) 
{ 
    @($Item2) * $Item1 
} 
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