Misleading PowerShell Exceptions–Example #1

In PowerShell 5.0 on Windows 10 was looking at a script with function not working:

Function Test-Condition($condition)
{
    
    if ([System.String]::IsNullOrWhiteSpace($condition))
    { 
        return $true 
    }
    
    switch ($conditon.ToLower())
    {
        "true" { return $true }
        "false" { return $false }
    }

    return (Invoke-Expression $condition)
}

The exception thrown by Powershell was:

You cannot call a method on a null-valued expression.
At C:\Users\chentiangemalc\Documents\Scripts\Test.ps1:5 char:9
+     if ([System.String]::IsNullOrWhiteSpace($condition))
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

The exception is misleading because it points to the wrong line of code. The actual error is in the switch line of code, $condition was misspelled into a a non-existent variable, throwing the “cannot call a method on a null-valued expression” exception.

If the script had started with

Set-StrictMode -Version Latest

We would get a more accurate exception:

The variable ‘$conditon’ cannot be retrieved because it has not been set.
At C:\Users\chentiangemalc\Documents\Scripts\Test.ps1:11 char:13
+     switch ($conditon.ToLower())
+             ~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (conditon:String) [], RuntimeException
    + FullyQualifiedErrorId : VariableIsUndefined

About chentiangemalc

specializes in end-user computing technologies. disclaimer 1) use at your own risk. test any solution in your environment. if you do not understand the impact/consequences of what you're doing please stop, and ask advice from somebody who does. 2) views are my own at the time of posting and do not necessarily represent my current view or the view of my employer and family members/relatives. 3) over the years Microsoft/Citrix/VMWare have given me a few free shirts, pens, paper notebooks/etc. despite these gifts i will try to remain unbiased.
This entry was posted in Debugging, PowerShell and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s