Scopes

PowerShell utilizes multiple scopes that you should be aware of when scripting. Usually, there is no need to interact with them, as PowerShell handles scoping automatically. The following scopes can be used:

$global:

The outermost scope. Visible in all child scopes.

$script:

Child scope of global, and the outer scope of a script.

$local:

Child scope of script, and the outer scope of a script block.

$private:

A scope that is not visible in any child scopes.

$using:

A special scope that allows for accessing data from within remote sessions.

$inGlobalScope = 'global'
$private:NoOneShallSeeMe = 'hidden'
function ChildOfGlobal
{
# can read outer variables that are not private
Write-Host "Outer variable value: $inGlobalScope"

# Without scope modifier, cannot write to outer scope
# What happens: A variable $local:inGlobalScope is created
# The output is misleading
$inGlobalScope = 'local'
Write-Host "Outer variable value: $inGlobalScope"
Write-Host "Actually, `$local:inGlobalScope was used: $local:inGlobalScope"
Write-Host "Private variable: $private:NoOneShallSeeMe"
}

ChildOfGlobal
Write-Host "Outer variable after function: $inGlobalScope"
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.234.62