Powershell: Get-Command fails with unexpected error when given a blank command-name argument

Created on 3 Aug 2020  路  5Comments  路  Source: PowerShell/PowerShell

Note: This is definitely a minor bug that won't arise too often in the real world.

Passing an all-whitespace -Name argument to Get-Command results in unexpected error message Get-Command: Index was outside the bounds of the array.

Steps to reproduce

{ Get-Command -ea Stop -Name ' '  } | Should -Throw -ErrorId CommandNotFoundException

Expected behavior

The test should succeed; that is, the usual CommandNotFoundException should be reported.

Actual behavior

The test fails, because the error mentioned above is reported instead.

Expected an exception, with FullyQualifiedErrorId 'CommandNotFoundException' to be thrown, 
but the FullyQualifiedErrorId was 
'System.IndexOutOfRangeException,Microsoft.PowerShell.Commands.GetCommandCommand'

Environment data

PowerShell Core 7.1.0-preview.5
Area-Cmdlets-Core First-Time-Issue Issue-Bug Up-for-Grabs

Most helpful comment

This issue could benefit from the proposed enhancement in #10010 to have [ValidateNotNullOrEmpty()] have a settable property to check for whitespace in addition to null and empty.

All 5 comments

I'll try tackling this one.

This issue could benefit from the proposed enhancement in #10010 to have [ValidateNotNullOrEmpty()] have a settable property to check for whitespace in addition to null and empty.

I'd like to point out that when reproducing this error after doing Start-DevPowershell it gives a different error. This is because src\System.Management.Automation\engine\CommandSearcher.cs has the following Dbg.Assert( !string.IsNullOrEmpty(name), "Caller should verify name");.

My question is, does this assert belong here? Issue #10165 was closed because it was decided that variable names and alias names with whitespace should be possible. So should Get-Command return the whitespace alias if it exists?

Given the conclusion to that issue, I'd agree that that assertion shouldn't be there, yeah. 馃憤

Well I've done some digging and it looks like in CommandSearcher.cs at line 1540 _commandName is trimmed _commandName = _commandName.TrimEnd(Utils.Separators.PathSearchTrimEnd);. This is what ultimately causes the index out of range exception to be thrown at line 1102 if (_commandName[0] == '.' || _commandName[0] == '~' || _commandName[0] == '\\') . If I comment out the _commandName.TrimEnd(Utils.Separators.PathSearchTrimEnd); The behavior of Get-Command ' ' is as expected and everything else _seems_ to work fine.

My next question is (and I realize this is asking a lot), does anyone have any ideas why the _commandName = _commandName.TrimEnd(Utils.Separators.PathSearchTrimEnd); is there?

Was this page helpful?
0 / 5 - 0 ratings