In PowerShell (PS), variables are used to storing variables like in other programming languages. All variables begin with “$” and the “=” operator is used to assign a value, for example, “$index = 1”. PS support a huge number of variable types.
The typical variables are strings, numbers, text, decimals, integers, arrays. Also you can use advanced types like IPAddress.
With Arrays is almost the same as assignment with other types, for example:
$IntArray = 1, 2, 3, 4;
$StringArray = “A”, “B”, “C”, “D”;
To add data in array is simple, you need to use the “+”
$IntArray = $IntArray + 5;
$StringArray = $StringArray + “E”;
Join arrays is simple to:
$IntArray = $IntArray + $SecondIntArray;
PS also accept multiple assignment:
$parameters = “sample1;value1;relation1”;
$sample, $value, $relation = $parameters.split(“;”);
or like this:
$sample, $extradata = $parameters.split(“;”);
$value = $extradata[0];
$relation = $extradata[1];
Also you can remove variable with Remove-Item and variable name without $:
Remove-Item Variable:\VariableName;
or with alias:
rv VariableName;
Variable Scope
The default scope is always the enclosing container of the variable.
If outside the script, or other general container the scope is global.
If you have the same value in different scopes is necessary to prefixed
the variable with the scope “global” or “local”, for example:
$variable = “I’m Global”;
function functionTest{
$variable = “I’m Local”;
Write-Host $global:variable;
Write-Host $local:variable;
Write-Host $variable;
}
functionTest;
Write-Host $global:variable;
Write-Host $local:variable;
Write-Host $variable;