Home > Enterprise >  How to change Script-scoped variable with function in powershell?
How to change Script-scoped variable with function in powershell?

Time:05-04

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

CodePudding user response:

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 are 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

CodePudding user response:

it's $script:num01 = $num02

as Santiago Squarzon wrote in comments.

  • Related