madknacker
madknacker

Reputation: 81

If statement never evaluates false when it should

Another amateur issue with a script I am working on. I am having an issue with exiting my script and console from within an If statement.

I have tried exit, exit(), $host.exit and [Environment]::Exit(1) within my Else portion. No matter what the user input is, the if statement continues.

I feel like I am missing something very simple but I can't figure it out. I only want it to continue if the user enters "Y" or "y". Anything else I just want it to fail and close...

I have also called $confirm after the user input make sure it's capturing the correct letter, which is is.

Here is the portion of the script that is failing:

$confirm = Read-Host "Continue deletion? [Y/N]"

if ($confirm -eq "Y" -or "y") {
    for ($i = 0; $i -le 4; $i++) {
        Get-ChildItem -Path $path0, $path1 -Filter "$dval*"| 
        % { Write-Host 'Deleting' $_.FullName $dval; Remove-Item $_.FullName -Recurse }
        $dval++ } 

} else { [Environment]::Exit(1) }

Upvotes: 2

Views: 59

Answers (1)

Matt
Matt

Reputation: 46690

The following statement is not doing what you think its doing.

if ($confirm -eq "Y" -or "y")

The issue here is that there are two separate statements being tested here that you might not expect $confirm -eq "Y" and "y". The latter would evaluate one its own as true since it is a non empty non null string.

Consider this lonely statement [bool]"y" which would return True.

So what you meant to write was $confirm -eq "Y" -or $confirm -eq "y". However that is redundant since -eq is case-insensitive by default. So $confirm -eq "Y" would suffice on its own.

Additional reading would be about how about_Logical_Operators work. It has some simple examples of how to chain multiple comparisons. To say the left hand side is evaluated independently of the right would be incorrect.

The PowerShell logical operators evaluate only the statements required to determine the truth value of the statement. If the left operand in a statement that contains the and operator is FALSE, the right operand is not evaluated. If the left operand in a statement that contains the or statement is TRUE, the right operand is not evaluated.

With your code entering any letter or value has no effect since -or "y" is always true. Entering any non-y value with the updated answer would make $confirm -eq "y" return False


If there was a reason to evaluate multiple distinct possibilities you would be looking at -contains or -in. I will leave it to you to look further into those (to keep the tangents down)

$confirm -in "y","m","b"

Where Y=Yes, M=Maybe and B=Bagel

Upvotes: 7

Related Questions