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.
The Set-ItemProperty cmdlet changes the value of the property of the specified item. You can use the cmdlet to establish or change the properties of items. For example, you can use Set-ItemProperty to set the value of the IsReadOnly property of a file object to $True .
To get the properties of an object, use the Get-Member cmdlet. For example, to get the properties of a FileInfo object, use the Get-ChildItem cmdlet to get the FileInfo object that represents a file. Then, use a pipeline operator ( | ) to send the FileInfo object to Get-Member .
In PowerShell, Set is an alias for the Set-Variable cmdlet, but it doesn't work with environment variables. Instead, you have to use the Get-ChildItem, Get-Item, or Remove-Item cmdlet with the ENV: drive.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With