1

I am currently working on a PowerShell script that interacts with a SQL Server database, at one point I need to see if there is a customer by the same name in the table, as such I am running the following query from PowerShell.

NB. Invoke-SQL is a helper function which calls Invoke-SQLCMD with specified parameters and allows database calls to be turned off with a global $Testing flag

$Customercount = Invoke-SQL "SELECT Count(Cust_ID) FROM Customers WHERE Cust_Name LIKE '$CustName'"

This correctly returns an object which can be read with $Customercount.itemarray however when this returns a 0 the matching fails as per the example below.

PS> $CustName = "Joe Bloggs"
PS> $Customercount = Invoke-SQL "SELECT Count(Cust_ID) FROM Customers WHERE Cust_Name LIKE '$CustName'"
PS> $Customercount.itemarray
0
PS> if ($Customercount.itemarray -eq 0) {Write-Host "equals 0"}
PS> if ($Customercount.itemarray -eq '0') {Write-Host "equals 0"}
PS> if ($Customercount.itemarray -eq "0") {Write-Host "equals 0"}
PS> if ($Customercount.itemarray -eq $Null) {Write-Host "equals 0"}
PS> $CustName = "Gael Test" 
PS> $Customercount = Invoke-SQL "SELECT Count(Cust_ID) FROM Customers WHERE Cust_Name LIKE '$CustName'"
PS> $Customercount.itemarray
1
PS> if ($Customercount.itemarray -eq 1) {Write-Host "equals 1"}     
equals 1
PS> 

I feel like I am missing something fundamental here but I haven't been able to place it, can anyone shed light on what I'm missing

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

2

If the left operarand is a collection, the comparison operator will work as a "filter" (see here). So basically, what happens is, if itemarray contains a single zero, then the filter -eq 0 will also return a single zero.

So, this ..

if ($Customercount.itemarray -eq 0) 

basically becomes this..

if (@(0))

which, since it's only a single item, is evaluated as

if (0)

...which evaluates to false.

marsze
  • 15,079
  • 5
  • 45
  • 61
  • 1
    Indeed,`[bool] @(0)` is `$false`, which isn't exactly obvious. The bottom section of [this answer](https://stackoverflow.com/a/53108138/45375) summarizes all the implicit to-Boolean conversion rule. – mklement0 Oct 26 '21 at 21:04
  • 1
    @mklement0 Despite all my love for Powershell, I hate it a little bit for giving me such Javascript vibes here – marsze Oct 26 '21 at 21:07
  • 1
    :)............. – mklement0 Oct 26 '21 at 21:07