Author Posts

May 3, 2015 at 11:35 am

Hi,

I want to use variables in modules, and outside these modules.

ModuleA
This contains StringA

In ModuleB in need to use the StringA variable

Both these modules are started in program.ps1.

I Also need StringA in the program.

Who can help me?

Richard

May 3, 2015 at 1:35 pm

You can export variables from a module the same way you can export functions. This can be controlled either by the Export-ModuleMember cmdlet, or via a module manifest (the VariablesToExport key.)

Alternatively, you could have a Get- function in your module which returns a copy of the string variable. This way people can't modify the value of your module variable without going out of their way to do it.

May 5, 2015 at 12:50 pm

Hello Dave,

I've searched for a solution, but can't find any.

Can you please give an example for me?

ModuleA
This creates StringA

ModuleB
use the StringA variable

program.ps1.
Import-moduleA
Import-moduleB
Use StringA

May 5, 2015 at 6:17 pm

This is sort of a contrived example, and not something I'd recommend doing often. Exported variables are typically used for "Preference" variables, and if ModuleB had a dependency on ModuleA, then it probably shouldn't be relying on the calling script to import both modules.

In any case, here's what the code might look like:

# ModuleA.psm1:

$script:StringA = 'Initial Value'

function Get-StringAFromModuleA
{
    return $script:StringA
}

Export-ModuleMember -Function Get-StringAFromModuleA -Variable StringA

# ModuleB.psm1:

function Get-StringAFromModuleB
{
    return $global:StringA
}

function Set-StringAFromModuleB
{
    $global:StringA = 'Set in Module B'
}

#program.ps1

Import-Module $PSScriptRoot\ModuleA.psm1 -Force
Import-Module $PSScriptRoot\ModuleB.psm1 -Force

$VerbosePreference = 'Continue'

Write-Verbose 'Get-StringAFromModuleA'
Get-StringAFromModuleA

Write-Verbose 'Get-StringAFromModuleB'
Get-StringAFromModuleB

Write-Verbose 'Set variable from ps1 script'
$global:StringA = 'Set from program.ps1'

Write-Verbose 'Get-StringAFromModuleA'
Get-StringAFromModuleA

Write-Verbose 'Get-StringAFromModuleB'
Get-StringAFromModuleB

Write-Verbose 'Set variable from module B'
Set-StringAFromModuleB

Write-Verbose 'Get-StringAFromModuleA'
Get-StringAFromModuleA

Write-Verbose 'Get-StringAFromModuleB'
Get-StringAFromModuleB

Notice that ModuleB and program.ps1 are both accessing a $global:StringA variable. However, when they modify that value, in ModuleA, it gets assigned to that same variable in the $script: scope. (If the variable had not been exported with Export-ModuleMember in ModuleA, then ModuleA's $script: scoped version of the variable would have remained set to 'Initial Value' the entire time, and program.ps1 / ModuleB would not have seen the value at all, until one of them had written something new to $global:StringA.)

May 6, 2015 at 12:03 am

Thank you very much, Dave !