PowerShell 3 bug with stack trace

I found another PowerShell 3 bug

Let’s create the following Script.ps1 script

[CmdletBinding()]
param
(
)

$script:ErrorActionPreference = "Stop"

$null.ToString()

if we run it in PowerShell 3 we will see

C:\Scripts\Script.ps1 : You cannot call a method on a null-valued expression.
At line:1 char:1
+ C:\Scripts\Script.ps1
+ ~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Script.ps1], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull,Script.ps1

As you see stacktrace here shown as At line:1 char:1.

If we run the same script from PowerShell 2

ToString : You cannot call a method on a null-valued expression.
At C:\Scripts\Script.ps1:8 char:15
+ $null.ToString <<<< ()
    + CategoryInfo          : InvalidOperation: (ToString:String) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : InvokeMethodOnNull

which is much better, it shows real stacktrace

I found that if we comment line #1 or #6, PowerShell 3 shows stacktrace a bit better

ToString : You cannot call a method on a null-valued expression.
At C:\Scripts\Script.ps1:8 char:1
+ $null.ToString <<<< ()
    + CategoryInfo          : InvalidOperation: (ToString:String) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : InvokeMethodOnNull

it shows correct line but still incorrect column. And I could not find a way to show column properly.

But I found a workaround how to show line properly and keep lines #1 and #6 unchanged.

You just need to insert Trap statement it will now work

[CmdletBinding()]
param
(
)

$script:ErrorActionPreference = "Stop"
Trap { throw $_ }
$null.ToString()

I create a bug for Microsoft.
Please vote for it if possible.
https://connect.microsoft.com/PowerShell/feedback/details/773611/powershell-3-bug-with-stack-trace

Advertisements

About mnaoumov

Senior .NET Developer in Readify
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

One Response to PowerShell 3 bug with stack trace

  1. Jefferson says:

    Generally I don’t learn article on blogs, however I wish to say that this write-up very pressured me to check out and do so! Your writing taste has been amazed me. Thanks, very great article.

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