PowerShell / PowerShell/PowerShell

Import-Module -Scope Local -Force in nested scripts removes the module from outer scripts

Open
#20,114 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Needs-Triage
Dominant language
C#
Stars
55.5k
Forks
8.5k
Avg merge
1d 2h
Merged PRs (30d)
88

Description

Prerequisites
Steps to reproduce

When using Import-Module -Scope Local in nested scripts, the module gets removed from the calling script after calling a script which also contains Import-Module -Scope Local for the same module.

MyModule.psm1 contents:

function Test-Something
{
    Write-Host "Test-Something called"
}

OuterScript.ps1 contents:

import-module -Scope Local -Force .\MyModule.psm1

Test-Something

.\InnerScript.ps1

Test-Something

InnerScript.ps1 contents:

import-module -Scope Local -Force .\MyModule.psm1

Write-Host "In InnerScript.ps1, module imported."
Expected behavior
PS D:\Source\Powershell\ImportModuleRepro> .\OuterScript.ps1
Test-Something called
In InnerScript.ps1, module imported.
Test-Something called
Actual behavior
PS D:\Source\Powershell\ImportModuleRepro> .\OuterScript.ps1
Test-Something called
In InnerScript.ps1, module imported.
Test-Something: D:\Source\Powershell\ImportModuleRepro\OuterScript.ps1:7
Line |
   7 |  Test-Something
     |  ~~~~~~~~~~~~~~
     | The term 'Test-Something' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct
     | and try again.
Error details
PS D:\Source\Powershell\ImportModuleRepro> get-error

Exception             :
    Type        : System.Management.Automation.CommandNotFoundException
    ErrorRecord :
        Exception             :
            Type    : System.Management.Automation.ParentContainsErrorRecordException
            Message : The term 'Test-Something' is not recognized as a name of a cmdlet, function, script file, or executable program.
                      Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
            HResult : -2146233087
        TargetObject          : Test-Something
        CategoryInfo          : ObjectNotFound: (Test-Something:String) [], ParentContainsErrorRecordException
        FullyQualifiedErrorId : CommandNotFoundException
        InvocationInfo        :
            ScriptLineNumber : 7
            OffsetInLine     : 1
            HistoryId        : 9
            ScriptName       : D:\Source\Powershell\ImportModuleRepro\OuterScript.ps1
            Line             : Test-Something
            PositionMessage  : At D:\Source\Powershell\ImportModuleRepro\OuterScript.ps1:7 char:1
                               + Test-Something
                               + ~~~~~~~~~~~~~~
            PSScriptRoot     : D:\Source\Powershell\ImportModuleRepro
            PSCommandPath    : D:\Source\Powershell\ImportModuleRepro\OuterScript.ps1
            InvocationName   : Test-Something
            CommandOrigin    : Internal
        ScriptStackTrace      : at <ScriptBlock>, D:\Source\Powershell\ImportModuleRepro\OuterScript.ps1: line 7
                                at <ScriptBlock>, <No file>: line 1
    CommandName : Test-Something
    TargetSite  :
        Name          : LookupCommandInfo
        DeclaringType : System.Management.Automation.CommandDiscovery, System.Management.Automation, Version=7.3.6.500, Culture=neutral, PublicKeyToken=31bf3856ad364e35
        MemberType    : Method
        Module        : System.Management.Automation.dll
    Message     : The term 'Test-Something' is not recognized as a name of a cmdlet, function, script file, or executable program.
                  Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
    Data        : System.Collections.ListDictionaryInternal
    Source      : System.Management.Automation
    HResult     : -2146233087
    StackTrace  :
   at System.Management.Automation.CommandDiscovery.LookupCommandInfo(String commandName, CommandTypes commandTypes, SearchResolutionOptions searchResolutionOptions, CommandOrigin commandOrigin,
ExecutionContext context)
   at System.Management.Automation.ExecutionContext.CreateCommand(String command, Boolean dotSource)
   at System.Management.Automation.PipelineOps.AddCommand(PipelineProcessor pipe, CommandParameterInternal[] commandElements, CommandBaseAst commandBaseAst, CommandRedirection[] redirections, ExecutionContext
context)
   at System.Management.Automation.PipelineOps.InvokePipeline(Object input, Boolean ignoreInput, CommandParameterInternal[][] pipeElements, CommandBaseAst[] pipeElementAsts, CommandRedirection[][]
commandRedirections, FunctionContext funcContext)
   at System.Management.Automation.Interpreter.ActionCallInstruction`6.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
TargetObject          : Test-Something
CategoryInfo          : ObjectNotFound: (Test-Something:String) [], CommandNotFoundException
FullyQualifiedErrorId : CommandNotFoundException
InvocationInfo        :
    ScriptLineNumber : 7
    OffsetInLine     : 1
    HistoryId        : 9
    ScriptName       : D:\Source\Powershell\ImportModuleRepro\OuterScript.ps1
    Line             : Test-Something
    PositionMessage  : At D:\Source\Powershell\ImportModuleRepro\OuterScript.ps1:7 char:1
                       + Test-Something
                       + ~~~~~~~~~~~~~~
    PSScriptRoot     : D:\Source\Powershell\ImportModuleRepro
    PSCommandPath    : D:\Source\Powershell\ImportModuleRepro\OuterScript.ps1
    InvocationName   : Test-Something
    CommandOrigin    : Internal
ScriptStackTrace      : at <ScriptBlock>, D:\Source\Powershell\ImportModuleRepro\OuterScript.ps1: line 7
                        at <ScriptBlock>, <No file>: line 1
Environment data
PS D:\Source\Powershell\ImportModuleRepro> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      7.3.6
PSEdition                      Core
GitCommitId                    7.3.6
OS                             Microsoft Windows 10.0.19045
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0
Visuals

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the reported OuterScript.ps1, InnerScript.ps1, and MyModule.psm1 reproduction with Import-Module -Scope Local -Force. Trace how the nested import affects command availability in the outer script. Done means the final Test-Something call succeeds while preserving the reported inner-script behavior, with regression coverage added for this scenario.

Written by the indexing model from the issue text.

Assessment

Tech stack
powershell
Domain
cli
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.