-
Notifications
You must be signed in to change notification settings - Fork 29
/
Add-ScopeLevel.ps1
68 lines (54 loc) · 1.41 KB
/
Add-ScopeLevel.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<#
.SYNOPSIS
Convert a scope level to account for another call stack level.
.DESCRIPTION
For scripts that need to get or set a variable of a specific scope so that it disappears at
the end of a block/function/script, or so that it persists globally, this calculates the
additional call level added by that script.
.INPUTS
System.String containing the desired level.
.OUTPUTS
System.String containing the calculated level (Global or an integer).
.LINK
Stop-ThrowError.ps1
.LINK
Get-PSCallStack
.LINK
about_Scopes
.FUNCTIONALITY
PowerShell
.EXAMPLE
Add-ScopeLevel.ps1 Local
1
.EXAMPLE
Add-ScopeLevel.ps1 3
4
.EXAMPLE
Add-ScopeLevel.ps1 Global
Global
#>
#Requires -Version 3
[CmdletBinding()][OutputType([string])] Param(
# The requested scope from the caller of the caller of this script.
# Global, Local, Private, Script, or a positive integer.
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)][string] $Scope
)
Process
{
if($Scope -match '\A\d+\z') {return "$(1+[int]$Scope)"}
switch($Scope)
{
Global {return 'Global'}
Local {return '1'}
Private {return '1'}
Script
{
$stack = Get-PSCallStack
for($i = 2; $i -lt $stack.Length; $i++)
{
if($stack[$i].Command -and $stack[$i].FunctionName -like '<ScriptBlock>*') {return "$($i-1)"}
}
Stop-ThrowError.ps1 'Unable to find Script scope' -Argument Scope
}
}
}