This is one of those examples where it’s important to read up as much as possible when developing in a language/platform we don’t know. It’s common to assume concepts based on what we already know from other languages, but sometimes that can backfire. In this case I’m going to show a very simple example where I wrongly assumed how something as simple as a comparison operator works.
I ran into this problem while writing a test as I was practicing TDD. To keep it simple, this is the simplest example I can think of to show how wrong I was:
$a = @("item1", "item2")
if ($a -eq $a) { Write-Host "$a is equal to $a" }
else { Write-Host "$a is not equal to $a" }
Assuming that -eq is the equality operator, someone who doesn’t know PowerShell but does know other programming languages could assume that this sample script would go into the if instead of the else. That was exactly my mistake. If I run this script in PowerShell, it will print “item1 item2 is not equal to item1 item2”.
If I had bothered to read the PowerShell documentation I would have seen that the -eq operator is quite peculiar and actually does something more complicated. Although I recommend reading the original source, this is a short summary:
- If both variables are strings, it applies a case-insensitive comparison and returns $true or $false
- If the left one is an array of strings @(“item1”, “item2”) and the right one is a string “item1”, it will look for “item1” in the array and return @(“item1”)
- If on the left we have an array of strings @(“item1”, “item2”) and on the right an array of strings with a single item @(“item1”), it will return @(“item1”)
- As we saw at the beginning, if we have two arrays of strings, even if they are equal, it will return @()
- Some of the examples above give different results if we swap the variables, left for right. If you want to know them, try it! 😉
Conclusion: you have to read more. For me, reading other people’s code helps a lot. Studying how Pester or Psake are built has let me understand the good parts of PowerShell much better.