Skip to content

ArgumentOutOfRangeException in Compiler.LoadModule  #4695

@powercode

Description

@powercode

In some cases where a module is loaded with
using module <path>
and there is an error loading the module, we can end up with a case where PowerShell HadErrors is true, but there are no errors in the powershell.Streams.Errors.

This causes an index out of range when we try to throw.

            var commandInfo = new CmdletInfo("Import-Module", typeof(ImportModuleCommand));
            var ps = PowerShell.Create(RunspaceMode.CurrentRunspace)
                .AddCommand(commandInfo)
                .AddParameter("Name", modulePath)
                .AddParameter("PassThru");
            var moduleInfo = ps.Invoke<PSModuleInfo>();
            if (ps.HadErrors)
            {
                var errorRecord = ps.Streams.Error[0];
                throw InterpreterError.NewInterpreterException(modulePath, typeof(RuntimeException), null,
                    errorRecord.FullyQualifiedErrorId, errorRecord.ToString());
            }

I haven't figured out yet what is causing the error, and it is harder to diagnose since this error masks the underlying condition.

Steps to reproduce

# mod.psm1
$c = Get-Command -CommandType Application -Name Foobar.nonexisting -ErrorAction SilentlyContinue

######

PS> using module .\mod.psm1

Expected behavior

get-command : The term 'Foobar.nonexisting' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At mod.psm1 line:1 char:1
+ get-command nonexisting -CommandType Application
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (nonexisting:String) [Get-Command], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand

Or some

Actual behavior

An error occurred while creating the pipeline.
At line:0 char:0

This is a really unhelpful error message :)

$error[0] | fl -showerror -force *
Message        : Index was out of range. Must be non-negative and less than the size of the collection.
                 Parameter name: index
ActualValue    :
ParamName      : index
Data           : {}
InnerException :
TargetSite     : Void ThrowArgumentOutOfRangeException(System.ExceptionArgument, System.ExceptionResource)
StackTrace     :    at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
                    at System.Collections.Generic.List`1.get_Item(Int32 index)
                    at System.Management.Automation.PSDataCollection`1.get_Item(Int32 index)
                    at System.Management.Automation.Language.Compiler.LoadModule(PSModuleInfo originalModuleInfo)
                    at System.Management.Automation.Language.Compiler.LoadUsingsImpl(IEnumerable`1 usingAsts, Assembly[]& assemblies)
                    at System.Management.Automation.Language.Compiler.GenerateLoadUsings(IEnumerable`1 usingStatements, Boolean allUsingsAreNamespaces, List`1 exprs)
                    at System.Management.Automation.Language.Compiler.GenerateTypesAndUsings(ScriptBlockAst rootForDefiningTypesAndUsings, List`1 exprs)
                    at System.Management.Automation.Language.Compiler.CompileSingleLambda(ReadOnlyCollection`1 statements, ReadOnlyCollection`1 traps, String funcName, IScriptExtent entryExtent, IScr
                 iptExtent exitExtent, ScriptBlockAst rootForDefiningTypesAndUsings)
                    at System.Management.Automation.Language.Compiler.CompileNamedBlock(NamedBlockAst namedBlockAst, String funcName, ScriptBlockAst rootForDefiningTypes)
                    at System.Management.Automation.Language.Compiler.VisitScriptBlock(ScriptBlockAst scriptBlockAst)
                    at System.Management.Automation.Language.Compiler.Compile(CompiledScriptBlockData scriptBlock, Boolean optimize)
                    at System.Management.Automation.CompiledScriptBlockData.ReallyCompile(Boolean optimize)
                    at System.Management.Automation.CompiledScriptBlockData.CompileUnoptimized()
                    at System.Management.Automation.CompiledScriptBlockData.Compile(Boolean optimized)
                    at System.Management.Automation.DlrScriptCommandProcessor.Init()
                    at System.Management.Automation.CommandDiscovery.CreateCommandProcessorForScript(ExternalScriptInfo scriptInfo, ExecutionContext context, Boolean useNewScope, SessionStateInternal
                  sessionState)
                    at System.Management.Automation.CommandDiscovery.CreateScriptProcessorForSingleShell(ExternalScriptInfo scriptInfo, ExecutionContext context, Boolean useLocalScope, SessionStateIn
                 ternal sessionState)
                    at System.Management.Automation.CommandDiscovery.LookupCommandProcessor(CommandInfo commandInfo, CommandOrigin commandOrigin, Nullable`1 useLocalScope, SessionStateInternal sessio
                 nState)
                    at System.Management.Automation.CommandDiscovery.LookupCommandProcessor(String commandName, CommandOrigin commandOrigin, Nullable`1 useLocalScope)
                    at System.Management.Automation.Runspaces.Command.CreateCommandProcessor(ExecutionContext executionContext, CommandFactory commandFactory, Boolean addToHistory, CommandOrigin orig
                 in)
                    at System.Management.Automation.Runspaces.LocalPipeline.CreatePipelineProcessor()
HelpLink       :
Source         : mscorlib
HResult        : -2146233086

Environment data

All versions

Metadata

Metadata

Assignees

Labels

Issue-Discussionthe issue may not have a clear classification yet. The issue may generate an RFC or may be reclassifResolution-FixedThe issue is fixed.WG-Enginecore PowerShell engine, interpreter, and runtime

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions