Powershell and the Left Hand Side

To support me, you can subscribe to the channel, share and like the videos, disable your ad blocker or make a donation. Thank you!

A new article, to talk about an important notion in Powershell, the Left Hand Side (LHS) notion.
When using operators in Powershell, the type of the object to the left of the operator (LHS) defines the type of the object to the right (RHS: Right Hand Side).
Only elements of the same type can be compared, added, multiplied, etc.
If the type is different between LHS and RHS then Powershell tries to convert the RHS object to the same type as the LHS object, if it can’t, it throws an exception

# Example
$jackpot = 9
$number = Read-Host 'enter a number'
# Enter the number 10
if ( $number -le $jackpot )
{ "$number is smaller than $jackpot" }
else
{ "$number greater than $jackpot" }

The expected result is 9 is smaller than 10 but the result is 9 is equal to or greater than 10.
If we check the type of variables

$jackpot.GetType()
# $jackpot is an integer
$number.GetType()
# $number is a string

In the previous example, Powershell converts 10 into a string and compares 9 to 1, and 9 is much greater than 1.

# Note: -lt stands for lower than
9 -lt 10
PS > True
9 -lt '10'
PS > True
# 10 is converted to an integer
9 -lt 10
PS > False
# 10 is converted to a string
9 -lt 'foo'
PS > Exception, Powershell cannot convert foo to integer

Another example with the multiplication operator, an integer and a string

# You can multiply characters with a number
'#' * 10
PS > ##########
# But you can't multiply a number with characters
10 * '#'
PS > Exception, Powershell cannot convert # to an integer

One last example with the multiplication operator, an array and a string where the result will be different depending on the element in LHS

$Array = 'foo','bar'
'Hello ' + $Array
PS > Hello foo bar
# Powershell has managed to convert my array into a string
$Array + 'Hello '
PS > foo
PS > bar
PS > Hello
# Powershell added my string to my array

This is also why comparisons with $null must be placed on the left. To find out more about using $null, you can read Kevin Marquette’s (https://powershellexplained.com) article published on the Microsoft site.
https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-null#checking-for-null

Related links