Reputation: 77
I'm quite new to Powershell and working on a little project with functions. What I'm trying to do is creating a function that takes 2 arguments. The first argument ($Item1) decides the size of the array, the second argument ($Item2) decides the value of the indexes.
So if I write: $addToArray 10 5 I need the function to create a array with 10 indexes and the value 5 in each of them. The second argument would also have to take "text" as a value.
This is my code so far.
$testArray = @();
$indexSize = 0;
function addToArray($Item1, $Item2)
{
while ($indexSize -ne $Item1)
{
$indexSize ++;
}
Write-host "###";
while ($Item2 -ne $indexSize)
{
$script:testArray += $Item2;
$Item2 ++;
}
}
Any help is appreciated.
Kind regards Dennis Berntsson
Upvotes: 0
Views: 203
Reputation: 54821
And another one.
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
Upvotes: 1
Reputation: 68243
Here's another possibility:
function addToArray($Item1, $Item2)
{
@($Item2) * $Item1
}
Upvotes: 1
Reputation: 126712
There are many ways to accomplish that, here's a straightforward one (long version):
function addToArray($Item1, $Item2)
{
$arr = New-Object Array[] $Item1
for($i=0; $i -lt $arr.length; $i++)
{
$arr[$i]=$Item2
}
$arr
}
addToArray 10 5
Upvotes: 1