Explain variable / Array scope in PowerShell function.

PowerShellMicrosoft TechnologiesSoftware & Coding

Generally, when the variable is declared as a Public variable or outside the function in the script (not in any other variable or condition), you don’t need to pass that value to function because the function retains the value of the variable when the variable is initialized before the function is called.

Example

function PrintOut{
   Write-Output "your Name is : $name"
}
$name = Read-Host "Enter your Name"
PrintOut

In the above example, $name variable is declared outside the function called PrintOut. So as the variable can be read inside the function, you can directly use the variable by its name.

Output

Enter your Name: PowerShell
your Name is : PowerShell

On the contrary, when you have the $name variable declared inside and when you check the output outside the function, you won’t get the value of the variable.

Example

function PrintOut{
   $name = Read-Host "Enter your Name"
}
PrintOut
Write-Output "your Name is : $name"

Output

Enter your Name: PowerShell
your Name is :

You can see in the above output the value of the $Name is NULL as $name is declared inside the function.

On the other hand, if the variable or array is declared outside the function and when you modify the value of the variable or array inside the function, it doesn’t reflect outside of the function.

Example

function PrintOut{
   $name = Read-Host "Enter your Name"
   Write-Output "Name inside function : $name"
}
$name = "Alpha"
PrintOut
Write-Output "Name after calling function : $name"

Output

Enter your Name: PowerShell
Name inside function : PowerShell
Name after calling function : Alpha

As we observe here, $name variable value changes inside the function but doesn’t reflect the outside of the function because it has a limited scope.

Similarly, for the array,

$services = @()
function Automatic5Servc{
   $services = Get-Service | Where{$_.StartType -eq "Automatic"} | Select -First 5
}
Automatic5Servc
Write-Output "Automatic Services : $services"

In the above code, you won’t get the services information because the value of the Services array variable is null and function can’t update the original variable.

raja
Published on 17-Apr-2020 12:33:56
Advertisements