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?

7
  • 1
    it will work if you use $Global:errorMessages. Take a look at powershelll scope Commented May 2, 2019 at 14:43
  • Also read Get-Help about_If => elseif () Commented May 2, 2019 at 14:46
  • I did try it with the global scope as well, but it still does not work. Commented May 2, 2019 at 14:46
  • this >>> if($status = ($fName -eq $NAME) -and ($fSpeed -eq $SPEED)) <<< is an assignment, not a comparison. [grin] Commented May 2, 2019 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. Commented May 2, 2019 at 14:49

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

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.