How does ref work in powershell function?

Tominik

I am learning about passing by reference in powershell and scope of variable within a function and I don't understand how a variable can be changed without it being passed into the function. Can someone help explain how $b can be changed like this without it being passed to the function?

$a = 1
$b = 2

function add-one{
    param(
        [ref]$var
    )
    $var.value += 1
}

function add-two{
    param(
        [ref]$var
    )
    $donothing = $var.Value

    #How is $b visible inside this function?
    add-one -var ([ref]$b)
    add-one -var ([ref]$b)

}

add-two -var ([ref]$a)

$a
$b

I was expecting to get an error when calling add-one -var ([ref]$b) because its not in the scope. However I got this output:

1
4
SavindraSingh

In PowerShell Script there are two types of scopes, Script Scope and Function Scope. Any variable that you declare inside the same script file is accessible by all the functions using the Script Scope. However, when you change the value of a variable within a function, which was declared in Script Scope, that new value (that you assign within the function scope) is accessible within function scope. But when you try to access the value of a variable outside the function, it will still show the value you have assigned in the script scope.

In your code [ref] has nothing to do with the scope.

Adding below example to explain it better:

$scriptVar = "Value from script scope"
Write-Host "Initial value of scriptVar from Script scope = $scriptVar"

function Change-Value
{
    Write-Host "Initial value of scriptVar in 'Change-Value' function from Script scope = $scriptVar"
    $scriptVar = "New value from function"
    Write-Host "New value of scriptVar in 'Change-Value' function from Script scope = $scriptVar"
}

Change-Value

# Check value again after running the Change-Value function
Write-Host "Current value of scriptVar from Script scope after running 'Change-Value' function = $scriptVar"

This script will produce below output:

Initial value of scriptVar from Script scope = Value from script scope
Initial value of scriptVar in 'Change-Value' function from Script scope = Value from script scope
New value of scriptVar in 'Change-Value' function from Script scope = New value from function
Current value of scriptVar from Script scope after running 'Change-Value' function = Value from script scope
cope

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related