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

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Indeed,[bool] @(0) is $false, which isn't exactly obvious. The bottom section of this answer summarizes all the implicit to-Boolean conversion rule.
@mklement0 Despite all my love for Powershell, I hate it a little bit for giving me such Javascript vibes here
:).............

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.