2

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
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
Fedor Pinega
  • 73
  • 1
  • 8
  • 2
    You would need to use a scope modifier for this, `$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. – Santiago Squarzon May 03 '22 at 21:05
  • Santiago Squarzon thanks, that's what i needed! Originally there's a big script and a function sets its parameters depending on how it 's launched – Fedor Pinega May 03 '22 at 21:20

2 Answers2

3

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
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
0

it's $script:num01 = $num02

as Santiago Squarzon wrote in comments.

Fedor Pinega
  • 73
  • 1
  • 8