Search

PowerShell 3 bug with stack trace by Michael Naumov

Active

3
0
Sign in
to vote
Type: Bug
ID: 773611
Opened: 12/5/2012 5:48:57 PM
Access Restriction: Public
1
Workaround(s)
0
User(s) can reproduce this bug
If we run the following script in PowerShell 3, we will see a wrong stacktrace

===
[CmdletBinding()]
param
(
)

$script:ErrorActionPreference = "Stop"

$null.ToString()
===
Details (expand)
How often does this happen?
Always Happens

Have you seen this problem before in this product?

No, this is new to the most recent version
Reproduction Steps
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()
===
Expected Results
 
File Attachments
0 attachments
Sign in to post a comment.
Sign in to post a workaround.
Posted by Michael Naumov on 12/6/2012 at 1:16 AM
The following line is a workaround which works in both PowerShell 2 & 3

Trap { throw $_ }

Insert it in the top of your script