Have the script
[int] $num01 = 2
function setNo ([int] $num02)
{
$num01 = $num02;
}
write-host $num01
setNo -num02 4
write-host $num01
setNo -num02 6
write-host $num01
It produces an output
2
2
2
How to make it produce output:
2
4
6
There are several ways of altering the value of a variable outside the function's scope, for example:
[ref], see about_Ref:([ref] $num01).Value = $num02;
$script:num01 = $num02;
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 value type, it would not be the case if it was a reference type, e.g.: 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
$script:num01 = $num02, however it is very likely that there is a better and cleaner way of doing this if you explain what you're trying to accomplish or why it is required that you update a variable outside the function's scope.