Dukeyu
Dukeyu

Reputation: 59

how to call a variable from a function

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 ?

Upvotes: 1

Views: 73

Answers (2)

Theo
Theo

Reputation: 61028

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.

Upvotes: 1

Rob
Rob

Reputation: 103

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

Upvotes: 1

Related Questions