Search code examples
powershelloperatorsequality-operator

Powershell If then statement not working. How to fix logic?


I can't seem to get this 'if then' statement to work. What am I doing wrong with this simple statement.

$checkUS = "false"

$usRegions =(Get-EC2Region) |Where -Property RegionName -Like -Value "us-*" |select RegionName | foreach {$_.RegionName}
$allregions=(Get-EC2Region).RegionName

If($checkUS = "true") {$Regions=$usRegions} Else {$Regions=$allregions}

thanks!


Solution

  • In Powershell, the = operator is used for assignment.

    You need to use the -eq comparison operator when defining your IF condition.

    Wrong

    If($checkUS = "true") ...

    Correct

    If($checkUS -eq "true") ...

    .

    • The first part (the condition) need the comparison operators
    • The second part of the statement is performing variable assignments and therefore the = sign is the good call here. {$Regions=$usRegions} Else {$Regions=$allregions}

    Reference

    About Comparison Operators