Nicholas B
Nicholas B

Reputation: 1

PowerShell IF statement Variables

im curious how to use the IF statement logic further in my code. Let me elaborate with an example.

$a=1
$b=10000
    if(($a=1) -or ($b=1))
       {write-host ""}  #Here, I want to write what ever variable was $true
                        #in the if statement above.... so I want it to 
                        #write "1" which was $a and was $true in the if
                        #statement...

I could write more logic to accomplish this, but im wondering if the values that the if statement used can be used again in the code. Im thinking there is a "hidden" variable maybe?

Upvotes: 0

Views: 1642

Answers (1)

vonPryz
vonPryz

Reputation: 24071

($a=1) is usually an assignment statement. This is not the case in Powershell, but it sure looks like a bug. The Powershell way to do comparison is to use -eq. So,

if(($a -eq 1) -or ($b -eq1))

Now, the simple solution is a bit different. What happens, if both $a and $b happen to be 1?

$comp = 1 # Value to compare against
$a=1
$b=100
if($a -eq $comp) { write-host "`$a: $a" }
if($b -eq $comp) { write-host "`$b: $b" }

This approach is easy to understand, which is in most of the cases more important than other factors like speed.

Upvotes: 1

Related Questions