Why is Powershell 7 (pwsh.exe) NOT outputting the full error when we have a $null
passed to a non-null parameter? And how can I configure my Powershell 7 on my Windows 10 box to fully report it?
Given this script:
param(
[Parameter()]
$Adventurer = "Bilbo"
)
$ErrorActionPreference = 'Stop'
#Requires -Version 7
function Get-SpyResult($FileName) {
$profile = Get-Item $FileName
# ...
}
$x = Get-SpyResult $Adventurer
# ...
Write-Host "If this worked, we would get here."
We can observe the following:
PS C:temp> $PSVersionTable.PSVersion.ToString()
7.4.1
PS C:temp> .here_be_dragons.ps1 "Someone"
Get-Item: C:temphere_be_dragons.ps1:10
Line |
10 | $profile = Get-Item $FileName
| ~~~~~~~~~~~~~~~~~~
| Cannot find path 'C:tempSomeone' because it does not exist.
PS C:temp>
PS C:temp> .here_be_dragons.ps1 $Null
here_be_dragons.ps1: Cannot bind argument to parameter 'Path' because it is null.
PS C:temp> # Why ??
PS C:temp>
PS C:temp> $Error[0]
Get-Item: C:temphere_be_dragons.ps1:10
Line |
10 | $profile = Get-Item $FileName
| ~~~~~~~~~
| Cannot bind argument to parameter 'Path' because it is null.
PS C:temp>
As you can see, Cannot find path
is reported with a stack trace.
But Cannot bind argument to parameter
is not properly reported, you have to resolve the error object manually.
Now, by inspecting the error objects, we can get a clue:
When it works, we have this:
_> $Error[0].GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False ActionPreferenceStopException System.Management.Automation.RuntimeException
For the $null
mess we have:
_> $Error[0].GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False ErrorRecord System.Object
The actual error objects seem to be generated differently. But that still doesn’t explain what this is all about and how I can get my scripts to always report a stack trace.