Search code examples
powershelloperator-precedence

Variable holds previous value even when new value assigned


I am probably missing something simple but...

My code:

$BusinessUnits = @()
$Animal = 'DOG'

if (-not $BusinessUnits -contains $Animal) {
    $Animal + " NOT FOUND. ADDING"
    $BusinessUnits += $Animal
} else {
    $Animal + " FOUND"
}

$Animal = 'Mouse'
if (-not $BusinessUnits -Contains $Animal) {
    $Animal + " NOT FOUND. ADDING"
    $BusinessUnits += $Animal
} else {
    $Animal + " FOUND"
}
$BusinessUnits

Above code returns:

DOG NOT FOUND. ADDING
Mouse FOUND
DOG

The first if does not find DOG so adds it; however, the second if finds Mouse and does not add it. Mouse is NOT in the array at this point.

What have I done wrong?

I'm writing code to create a CSV file as part of some processing. The values for business unit will not be constant and may vary during processing. And I only want to write the header row when the first detail row is added.


Solution

  • The -not operator has higher precedence than the -contains operator, so you're effectively checking

    (-not $BusinessUnits) -contains $Animal
    

    rather than what you actually want to check

    -not ($BusinessUnits -contains $Animal)
    

    Use either parentheses (see above) or the -notcontains operator to avoid this gotcha.

    $BusinessUnits -notcontains $Animal