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?
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.
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.
Following are the different types of variables in the Windows PowerShell: User-Created Variables. Automatic Variables. Preference Variables.
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.
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
.
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