1
function test{
  for($a=0;$a -le 2;$a++){
     if($a -eq 1){break}
  }
}
#----outside----
write-output $a

How to call a variable from a function and not to use return to get $a ?

2 Answers 2

1

Aside from using scopes as described in Rob's answer, there is also the possibility to send a parameter by reference.

This means that inside the function, a reference to the original variable is used, so whatever the function does with it, the original value is affected.

The downside is that when using references, you must use the Value property of the System.Management.Automation.PSReference type to access/alter your data as in the example below:

function test ([ref]$a) {
  for ($a.Value = 0; $a.Value -le 2; $a.Value++){
     if ($a.Value -eq 1) {break}
  }
}

#----outside----
$a = 0 
test ([ref]$a)  # the parameter needs to be wrapped inside brackets and prefixed by [ref]
Write-Output $a

When sending a parameter that is an object type, like for instance a Hashtable, then by default it is always passed to the function by reference and for those you don't use the [ref] accellerator.

Sign up to request clarification or add additional context in comments.

Comments

1

Have you tried to set the variable global?

$var="Test"
function test()
{
    $global:var="blub"
}
test
$var

or

$a = 0

function test{
  for($global:a=0;$global:a -le 2;$global:a++){
     if($global:a -eq 1){break}
  }
}
test
write-output $a

1 Comment

The script scope will be enough I gather.

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.