Last active
May 30, 2019 20:31
-
-
Save FriedrichWeinmann/97108ea9c5828fe85bd0f47bd8e60d4d to your computer and use it in GitHub Desktop.
Demonstrates the scope pyramid for functions in Modules
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note:
Scope pyramid from within a module:
while calling commands outside of the module (such as
ForEach-Object
) may be part of the callstack, but are skipped in the scope pyramid