0

I am trying to add items to an array variable that I am declaring outside of a function.

Here is the idea of my code in a very simplified way:

function Test($NAME, $SPEED){
$fName = "testName"
$fSpeed = 100

if($status = ($fName -eq $NAME) -and ($fSpeed -eq $SPEED))
{}

else{
if($fName -ne $NAME)
{$errorMessages += "The name is not" + $NAME}

if($fSpeed -ne $SPEED)
{$errorMessages += "The speed is not" + $SPEED}
}
return $status
}

$script:errorMessages=@()
$result=@()

$result += Test -NAME "alice" -SPEED "100"
$result += Test -NAME "bob" -SPEED "90"
#result is an array of booleans that I need later on

$errorMessages

When I display $errorMessages, this is the expected output that I'd like:

The name is not alice
The name is not bob
The speed is not 90

However, when I try to display the variable outside of the function, and even outside of the "else" block, I get nothing printed out. How can I correctly add the error messages to the array?

Komputer
  • 51
  • 1
  • 16
  • 1
    it will work if you use $Global:errorMessages. Take a look at powershelll scope – guiwhatsthat May 02 '19 at 14:43
  • Also read `Get-Help about_If` => `elseif ()` –  May 02 '19 at 14:46
  • I did try it with the global scope as well, but it still does not work. – Komputer May 02 '19 at 14:46
  • this >>> `if($status = ($fName -eq $NAME) -and ($fSpeed -eq $SPEED))` <<< is an _assignment_, not a _comparison_. [*grin*] – Lee_Dailey May 02 '19 at 14:47
  • The reason why I'm not using elseif() is because I want to test each one of the conditions. If I use elseif, my example with "bob" will stop at the wrong name. – Komputer May 02 '19 at 14:49
  • Remove the brackets on `Test(-NAME "alice" -SPEED "100")` and `Test(-NAME "bob" -SPEED "90")` – Theo May 02 '19 at 14:51
  • Ah indeed, the brackets were a "typo" of me retyping the code on here. On my original code I do not have the brackets. Thank you. – Komputer May 02 '19 at 14:56

1 Answers1

1

You want to call errorMessages via the script scope. Therefore you've to use $script:errorMessage (instead of $errorMessage) inside your function.

function Test($NAME, $SPEED) {
   $fName = "testName"
   $fSpeed = 100
   $status = ($fName -eq $NAME) -and ($fSpeed -eq $SPEED)
   if (!$status) { 

       if ($fName -ne $NAME) { 
           $script:errorMessages += "The name is not" + $NAME 
       }

       if ($fSpeed -ne $SPEED) { 
           $script:errorMessages += "The speed is not" + $SPEED 
       }
   }
   $status
}

$errorMessages = @()
$result = @()

$result += Test -NAME "alice" -SPEED "100"
$result += Test -NAME "bob" -SPEED "90"
#result is an array of booleans that I need later on

$errorMessages

Now you get the expected output:

The name is notalice
The name is notbob
The speed is not90

Also be aware about the return statement in PowerShell -> stackoverflow answer

Hope that helps

Moerwald
  • 10,448
  • 9
  • 43
  • 83