0

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

3 Answers 3

1

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for posting this, it helps me get a increased understanding of Powershell.
1

Here's another possibility:

function addToArray($Item1, $Item2)
 {
   @($Item2) * $Item1
 }

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.