There are several ways of altering the value of a variable outside the function's scope, for example:
([ref] $num01).Value = $num02;
$script:num01 = $num02;
- Using
Set-Variable
with the -Scope Script
argument or $ExecutionContext
:
Set-Variable num01 -Value $num02 -Scope Script
# OR
$ExecutionContext.SessionState.PSVariable.Set('script:num01', $num02)
Note that, in this particular case, one of the above is necessary because the outside variable $num01
is a scalar, it would not be the case if it was a non-scalar, i.e. an array or hash table:
$num01 = @(2) # => array of a single element, index 0
function setNo ([int] $num02) {
$num01[0] = $num02 # => updating index 0 of the array
}
setNo 10; $num01 # => 10