powershellvariablesmodulepowershell-modulemodule-export

Why can't export variable members in a PowerShell module using VariablesToExport?


From How to Write a PowerShell Module Manifest I learned that I can export all the variables in the module using VariablesToExport = '*'. However, after using it, I found that I could not export any variables.

After writing tests to confirm and reading more documentation, I didn't find the cause of the problem. I may have overlooked something important. What is going on here?

TestModule.psm1 excerpt:

0..9 | ForEach-Object { New-Variable -Name "v_$_" -Value $_ }

TestModule.psd1 excerpt:

@{ModuleVersion = '1.0';RootModule = 'TestModule.psm1';VariablesToExport = '*'}

TestModule.Tests.ps1:

 # Confirm that the module has indeed been imported.
$ModuleName | Get-Module | ForEach-Object 'name' | Should -Be $ModuleName
 # All variables do not exist.
0..9 | ForEach-Object { "variable:v_$_" | Test-Path | Should -BeFalse }

Solution

  • It is far from obvious, but, as of PowerShell 7.2, in order to export variables from a PowerShell module, listing them in the module manifest's (*.psd1 file's) VariablesToExport entry alone is not enough:

    You also need an Export-ModuleMember -Variable call in your script module file (*.psm1) - be sure to place it at the end of the file, to ensure that all definitions to be exported have already been made.

    Caveat:

    E.g., to export all your $v_* variables, as well as all functions matching the name pattern *-Foo*, place the following at the bottom of your *.psm1 file:

    Export-ModuleMember -Variable v_* -Function *-Foo*
    

    Important:

    With a module that has a module manifest (*.psd1) - as is typical - and a script module (*.psm1), the export logic is a two-step process:


    Debugging tips: