Powershell: Error hidden when anonymous command uses `WriteError`

Created on 19 May 2020  Â·  6Comments  Â·  Source: PowerShell/PowerShell

Steps to reproduce

Paste into console (Error record arguments don't matter):

[CmdletBinding()] param() end {
$PSCmdlet.WriteError([Management.Automation.ErrorRecord]::new([Exception]::new(), '', 0, '')) }

Expected behavior

Exception of type 'System.Exception' was thrown.

Actual behavior

Nothing is shown. When calling $Error[0], this is shown:

Get-Command:
Line |
 201 |  … if ($myinv.MyCommand -and (Get-Command -Name $myinv.MyCommand -ErrorA …
     |                                                 ~~~~~~~~~~~~~~~~
     | Cannot validate argument on parameter 'Name'. The argument is null, empty, or an element of the argument collection contains a null value. Supply a collection that does not contain any null values and then try the command again.

Stringification probably shouldn't be relied on here, and $myinv.MyCommand.Name should be used instead.

Environment data

Name                           Value
----                           -----
PSVersion                      7.1.0-preview.2
PSEdition                      Core
GitCommitId                    7.1.0-preview.2
OS                             Microsoft Windows 10.0.18362
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0
Issue-Bug Resolution-Fixed WG-Engine

Most helpful comment

It is in ConciseView.

All 6 comments

It is in ConciseView.

At least in terms of symptom the following is similar, but also occurs in scripts:

# Should report the statement-terminating error that occurs during parameter
# binding, but doesn't:
& { [CmdletBinding()]param() } -Unsupported 

Hiding errors is a big deal. I wasted at least an hour figuring this same thing out today.
Can we either get this fixed ... or revert to NormalView by default for the next release?

It's a pretty simple fix, this:

$myinv.MyCommand -and (Get-Command -Name $myinv.MyCommand

needs to be

```powershell
$myinv.MyCommand.Name -and (Get-Command -Name $myinv.MyCommand.Name
````

in the format scriptblock.

Wouldn't that still be $null and still throw from Get-Command? 🤔

It would if it got there. It'll short circuit before running Get-Command if the above is done. The problem is that MyCommand isn't $null, just it's stringification.

Was this page helpful?
0 / 5 - 0 ratings