Steve Evans
Steve Evans

Reputation: 1148

Set Property in PowerShell Module

I have a PowerShell module called Test.psm1. I want to set a value on a variable and have that accessible when I call another method in that module.

#Test.psm1
$property = 'Default Value'

function Set-Property([string]$Value)
{
     $property = $Value
}

function Get-Property
{
     Write-Host $property
}

Export-ModuleMember -Function Set-Property
Export-ModuleMember -Function Get-Property

From PS command line:

Import-Module Test
Set-Property "New Value"
Get-Property

At this point I want it to return "New Value" but it's returning "Default Value". I have tried to find a way to set the scope of that variable but have not had any luck.

Upvotes: 7

Views: 4807

Answers (2)

Andrew Savinykh
Andrew Savinykh

Reputation: 26270

Jamey is correct. In your example, in the first line, $property = 'Default Value' denotes a file-scoped variable. In Set-Property function, when you assign, you assign to localy scoped variable that is not visible outside the function. Finally, in Get-Property, since there is no locally scoped variable with the same name the parent scope variable is read. If you change your module to

#Test.psm1
$property = 'Default Value'

function Set-Property([string]$Value)
{
         $script:property = $Value
}

function Get-Property
{
         Write-Host $property
}

Export-ModuleMember -Function Set-Property
Export-ModuleMember -Function Get-Property

As per Jamey's example, it will work. Note though that you don't have to use the scope qualifier in the very first line, as you are in the script scope by default. Also you don't have to use the scope qualifier in Get-Property, since the parent scope variable will be returned by default.

Upvotes: 12

Jamey
Jamey

Reputation: 1633

You're on the right track. You need to force the methods in the module to use the same scope when accessing $property.

$script:property = 'Default Value'
function Set-Property([string]$Value) { $script:property = $value; }
function Get-Property { Write-Host $script:property }
Export-ModuleMember -Function *

See about_Scopes for more info.

Upvotes: 3

Related Questions