Referring to variables created in a function


Trying to grasp the idea of variable scopes. I know a variable only exists inside a function and you would need to add $script:variablename to get the variable to be seen outside the function. So, from within the function and outside the function when I need the variable value do I always need to use $script:variablename or just $variablename?




Even if it’s possible it’s highly recommended not to use variables from another scope. But yes - if you specify a variable as for example GLOBAL you could access it from another scope without the scope modifier.

It’s better to provide a specific example on what you are trying to accomplish. Generally, you should not reference a global\script var like this:

#Bad, refrencing variables into a function
function Test-It {

    'Processing {0}' -f $Global:SomeVar

$Global:SomeVar = 'Some Value'

A better approach is to create a param:

#Good, create a param and pass it to the function
function Test-It {
    param (

    'Processing {0}' -f $SomeVar

$SomeVar = 'Some Value'
Test-It -SomeVar $SomeVar