powershellpowershell-7.2

How to export variables from a PowerShell module


I've defined a variable in a psm1 file but when I try to access it in another script, after importing the module, I'm not seeing the value set in the psm1 file.

globals.psm1

$blah = "hello world"

my-script.ps1

Import-Module "$PSScriptRoot\globals.psm1" -Force -Verbose
Write-Output "blah: ${blah}"

output

PS C:\blah> .\my-script.ps1
VERBOSE: Loading module from path 'C:\blah\globals.psm1'.
blah: ''

I thought all variables get exported by default. I must be interrupting this wrong:

Specifies the variables that the module exports to the caller's session state. Wildcard characters are permitted. By default, all variables ('*') are exported

source: MSFT Docs -> How to write a PowerShell module manifest
(CTRL + F on 'VariablesToExport' to find the quoted text)


And yes, if I export the variable, I can access it but the documentation says: 'By default, all varialbes ('*') are exported so what am I doing wrong or misunderstanding? 🤔

globals.psm1

$blah = "hello world"
Export-ModuleMember -Variable blah

Solution

  • Your module is not using a module manifest (a companion .psd1 file whose RootModule entry points to your .psm1 file in the case of script modules), whereas the documentation you quote pertains to module manifest-based modules.

    If a module consists only of a .psm1 file, and that file contains no Export-ModuleMember calls, the following rule applies:

    Caveat, if a manifest (.psd1) is used:

    Generally, exporting variables from modules is best avoided, because:


    To see which definitions a given module exports, pass -Verbose to the Import-Module call that imports it. Additionally, pass -Force in order to force re-loading of an already imported module.