Variables in modules in PowerShell
27,299
Function SetSQLServerAddr ([string] $name)
{
$SQLServer = $name
}
That creates a new local $SQLServer
in the scope of that function.
If you want to update a variable at module (.psm1
) scope then you need to prefix the name to indicate that:
Function SetSQLServerAddr ([string] $name)
{
$script:SQLServer = $name
}
For more on scopes see get-help about_scopes
.
Author by
user1866880
Updated on May 29, 2020Comments
-
user1866880 almost 4 years
I have a main script, where a few constants are defined. I then have a module (psm1) to include helper functions. The details are:
In the main script, I have imported the module as an object:
$cud2ADhleper = Import-Module -Force $cud2ADhelperModule -AsCustomObject
In the module, I have two variables,
[string]$SQLServer = $null Function SetSQLServerAddr ([string] $name) { $SQLServer = $name } Function GetSQLServerAddr { return $SQLServer }
My understanding is that because I am not exporting
$SQLServer
from the module, this variable should be local, and I should be able to Set/Get it.It turns out otherwise. After I called
SetSQLServerAddr ([string] $name)
, then calllingGetSQLServerAddr
returns $null. What did I miss?