Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables in modules in PowerShell

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 callling GetSQLServerAddr returns $null. What did I miss?

like image 394
user1866880 Avatar asked Jan 21 '13 13:01

user1866880


People also ask

What is the $_ variable in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.

Can you use variables in PowerShell?

In PowerShell, variables are represented by text strings that begin with a dollar sign ( $ ), such as $a , $process , or $my_var . Variable names aren't case-sensitive, and can include spaces and special characters.

What are the three types of variable in PowerShell?

Following are the different types of variables in the Windows PowerShell: User-Created Variables. Automatic Variables. Preference Variables.

How do I set variables in PowerShell?

PowerShell Variable Examples You can create a variable by simply assigning it a value. For example, the command $var4 = “variableexample” creates a variable named $var4 and assigns it a string value. The double quotes (” “) indicate that a string value is being assigned to the variable.


1 Answers

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.

like image 145
Richard Avatar answered Oct 17 '22 04:10

Richard