Skip to content

Instantly share code, notes, and snippets.

@FriedrichWeinmann
Last active May 30, 2019 20:31
Show Gist options
  • Save FriedrichWeinmann/97108ea9c5828fe85bd0f47bd8e60d4d to your computer and use it in GitHub Desktop.
Save FriedrichWeinmann/97108ea9c5828fe85bd0f47bd8e60d4d to your computer and use it in GitHub Desktop.
Demonstrates the scope pyramid for functions in Modules
New-Module -Name Test -ScriptBlock {
function Get-Test1
{
[CmdletBinding()]
param ()
$var = 24
$depth = 0
try
{
while ($variable = Get-Variable -Name var -Scope $depth -ErrorAction Ignore)
{
Write-Host (" Depth: {0:D2} | Value: {1:D3} | Callstack: {2}" -f $depth, $variable.Value, (Get-PSCallStack).Count)
$depth = $depth + 1
}
}
catch { }
}
function Get-Test2
{
[CmdletBinding()]
param (
)
$var = 12
1 .. 3 | ForEach-Object {
if ($_ -eq 1) { Get-Test1 }
}
}
function Get-Test3
{
[CmdletBinding()]
param (
)
$var = 7
Get-ExternalTest -Mode 1
}
$script:var = 6
} | Import-Module
$var = 3
function Get-ExternalTest
{
[CmdletBinding()]
param (
[ValidateSet('1', '2')]
[int]
$Mode = 1
)
$var = 42
switch ($Mode)
{
1 { Get-Test1 }
2 { Get-Test2 }
}
}
Write-Host "Test: Calling Get-Test2" -ForegroundColor Green
Get-Test2
Write-Host "Test: Calling Get-Test1" -ForegroundColor Green
Get-Test1
Write-Host "Test: Calling Get-Test3" -ForegroundColor Green
Get-Test3
# This shows, that the $var in Get-ExternalTest is NOT seen in te scope tree
Write-Host "Test: Calling Get-ExternalTest -Mode 2" -ForegroundColor Green
Get-ExternalTest -Mode 2
Write-Host "Test: Calling Get-ExternalTest -Mode 1" -ForegroundColor Green
Get-ExternalTest -Mode 1
@FriedrichWeinmann
Copy link
Author

Note:

  • Commands from other modules or no module at all are not part of the scope pyramid
  • There is no direct correlation between scopes and callstack!

Scope pyramid from within a module:

Global > Module (script) > Internal Command 1 > Internal Command 2 > … Internal Command N

while calling commands outside of the module (such as ForEach-Object) may be part of the callstack, but are skipped in the scope pyramid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment