-
Notifications
You must be signed in to change notification settings - Fork 1
/
Get-Scope.ps1
93 lines (72 loc) · 2.19 KB
/
Get-Scope.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
Function Get-Scope {
[Cmdletbinding()]
param (
)
$i = 0
do {
try {
$scopeId = $null
$scopeId = Get-Variable -Name Host -Scope $i -ErrorAction Stop
[pscustomobject]@{
ScopeId = $i
Type = $MyInvocation
}
$i++
}
catch {
Write-Verbose "ScopeId $i not found"
}
}
Until (-not($scopeId))
}
Function Nested {
Get-Scope
}
[System.Management.Automation.SessionState]::IsVisible([System.Management.Automation.CommandOrigin]::Runspace, $host)
[System.Management.Automation.SessionState] | Get-Member -Type Method -Static
$type = [PowerShell].Assembly.GetType('System.Management.Automation.Runspaces.LocalPipeline')
$method = $type.GetMethod(
'GetExecutionContextFromTLS',
[System.Reflection.BindingFlags]'Static,NonPublic'
)
$context = $method.Invoke(
$null,
[System.Reflection.BindingFlags]'Static,NonPublic',
$null,
$null,
(Get-Culture)
)
$type = [PowerShell].Assembly.GetType('System.Management.Automation.SessionStateInternal')
$constructor = $type.GetConstructor(
[System.Reflection.BindingFlags]'Instance,NonPublic',
$null,
$context.GetType(),
$null
)
$sessionStateInternal = $constructor.Invoke($context)
$method = $type.GetMethod(
'GetScopeByID',
[System.Reflection.BindingFlags]'Instance,NonPublic',
$null,
[string],
$null
)
$method.Invoke($sessionStateInternal,'GLOBAL')
$method = $type.GetMethod(
'get_ModuleScope',
[System.Reflection.BindingFlags]'Instance,NonPublic'
)
$method.Invoke()
$scope= $sessionStateInternal.GetType().DeclaredProperties | ?{$_.Name -eq 'ScriptScope'}
$type.GetMethods( [System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::NonPublic ) | % Name
function Get-ScriptBlockScope
{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[scriptblock]
$ScriptBlock
)
$flags = [System.Reflection.BindingFlags]'Instance,NonPublic'
[scriptblock].GetProperty('SessionStateInternal', $flags).GetValue($ScriptBlock) | select ScopeName
}