Skip to content

Is dot-sourcing .ps1 files with using statements from a .psm1 supported? #5942

@alx9r

Description

@alx9r

I'm looking for a supported way to reduce the namespace repetition I mentioned in #5940.

about_Using includes the following statement:

The using statement needs to be the first statement in the script.

Modules customarily dot-source individual .ps1 files from their .psm1. Pester is one such example. It's not clear to me how the above statement applies in the context of such a module.

Consider the following files:

UsingTest.psm1

@(
    'fileA.ps1'
    'fileB.ps1'
) |
    % { . "$(Split-Path -Path $MyInvocation.MyCommand.Path)\$_" }

function Get1 { [int][MyEnum]::One }

fileA.ps1

using namespace UsingTest.A

Add-Type @'
namespace UsingTest { namespace A {
    public enum MyEnum {
        One = 1,
        Two
    }
}
}
'@

function GetA1 { return [int][MyEnum]::One }

$script:v1 = 1

fileB.ps1

using namespace UsingTest.B

Add-Type @'
namespace UsingTest { namespace B {
    public enum MyEnum {
        One = 101,
        Two
    }
}
}
'@

function GetB1 { [int][MyEnum]::One }

function GetV1 { $script:v1 }
  1. Is this a supported use of using?
  2. Is it certain that GetA1 and GetB1 will return 1 and 101, respectively?
  3. How does the statement that "the using statement needs to be the first statement in the script" apply to such a module?
  4. Is there some other way large modules should be structured?

Edit: Add $script:v1 statements.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Questionideally support can be provided via other mechanisms, but sometimes folks do open an issue to get aResolution-AnsweredThe question is answered.WG-Languageparser, language semantics

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions