2013-11-09 40 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