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
2
  • 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. Commented May 3, 2022 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 Commented May 3, 2022 at 21:20

2 Answers 2

4

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 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
Sign up to request clarification or add additional context in comments.

Comments

1

it's $script:num01 = $num02

as Santiago Squarzon wrote in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.