Unexpected Results when Comparing Different Datatypes in PowerShell

Earlier this week, I saw a tweet from a fellow PowerShell community member who mentioned PowerShell was returning inaccurate results. The command shown in the tweet was similar to the one in the following example.

Why would results be returned where “IsFramework” is true when the command is filtering them down to only the ones that are false?

I knew exactly what the problem was because I’ve been bit by it more times than I care to remember. Piping the Get-AppxPackage command to Get-Member shows that the IsFramework property returns a Boolean and the results in the previous example where skewed because a string was being compared to a Boolean.

Simply changing the comparison value in the Where-Object statement from the string “False” to the Boolean $false returns the expected results as shown in the following example.

Because of the way implicit datatype conversion is performed in PowerShell, your mileage may vary depending on which way the comparison is being perform as shown in the following example where “False” is equal to $false, but $false isn’t equal to “False“.

Please post your questions, comments, and/or suggestions as a comment to this blog article.

µ

3 Comments

  1. Luke

    Unfortunately, some native PowerShell cmdlets are confusing because they are not switches and don’t use booleans.
    Get-NetFirewallRule -Enabled $true returns an error and you have to use Get-NetFirewallRule -Enabled ‘true’ instead.

    Reply
  2. Francesco Mantovani

    Man, I had exactly that problem regarding Firewall ports. Big thank you, I know understand why

    Reply

Leave a Reply to Luke Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: