powershell logical operators and $Error variable

powershell

Solution

`@mjolinor's` answer tries to explain it, but is incomplete.

When you do `(1,2,3) -eq 1`, you get back `1`. In this case what `-eq` does with an array is to return the element that is equal to the RHS, and nothing if no match occurs.

On the other hand, if you do `1 -eq (1,2,3)`, you get `False`, because the above occurs only when the array is the LHS. So it is not true that the `-eq` operator always does behaves like the above case when it comes to arrays.

Now, coming on to the `-ne` usage. When you do `(1,2,3) -ne 1`, you get the array `2,3`. That is, it returns the elements that are not equal to the RHS. And similar to `-eq`, `1 -ne (1,2,3)`, will return `True`

Coming to your condition - `($error -eq $null) -or ($error -ne $null)`

When `$error` is empty, `$error -eq $null` will return nothing ( and is hence `False` in a bool statement). This is of course because there is no element matching `$null` in $error. Also, `$error -ne $null` will also return nothing ( and hence is `False` in a bool statement) because $error is empty and there is no element in it that is not $null.

Hence, when `$error` is empty, your statement will be false and the block inside if will not be executed.

If `$error` were not empty, either of the condition would have been true, and you would have seen the `write-host`executed.

So how do you really solve this problem?

The straightforward way is to check the length of the `$error` array:

if($error.length -gt 0){
    write-host "error occured"
}

Also, read this article that talks about various error handling strategies - http://blogs.technet.com/b/heyscriptingguy/archive/2011/05/12/powershell-error-handling-and-why-you-should-care.aspx

Problem

Recently I had to check whether some errors occurred when my script is executed. First I've tried to check whether $Error is $null. The strange thing for me was that I haven't got any result from (neither True, nor False). Then i've wrote: ``` if (($error -eq $null) -or ($error -ne $null)) {Write-Host "NULL"} ``` And nothing was in the output. This made me very confused. I've found that such thing happens for all variables which are of System.Collections.ArrayList type. Maybe someone knows the explanation why this happens, because for me this looks like a bug? Version of Powershell, on which I found this, is 3.0.

Original source