Skip to content

Instantly share code, notes, and snippets.

@alx9r
Last active December 13, 2024 17:48
Show Gist options
  • Select an option

  • Save alx9r/c8f2062dcf82fa9b3f2527bd5aad52d9 to your computer and use it in GitHub Desktop.

Select an option

Save alx9r/c8f2062dcf82fa9b3f2527bd5aad52d9 to your computer and use it in GitHub Desktop.
function getSessionState {
param($ScriptBlock)
[scriptblock].
GetProperty('SessionStateInternal',
[System.Reflection.BindingFlags] 'NonPublic, Instance').
GetValue($ScriptBlock)
}
foreach ($method in 'call' ,
'steppable' ) {
foreach ($provenance in '{}' ,
'[scriptblock]::Create()',
'{}.Ast.GetScriptBlock()' ) {
$sb = $null
$before = $null
$after = $null
$sb =
$(switch ($provenance) {
'{}' {
switch ($method) {
'call' {{. {}}}
'steppable' {{. {}}}
}
}
'[scriptblock]::Create()' {[scriptblock]::Create({. {}})}
'{}.Ast.GetScriptBlock()' {{. {}}.Ast.GetScriptBlock()}
})
$before = getSessionState $sb
switch ($method) {
'call' {
& $sb
}
'steppable' {
. {
[CmdletBinding()]param()
$pipe = $sb.GetSteppablePipeline($MyInvocation.CommandOrigin,@())
$pipe.Begin($PSCmdlet)
$pipe.End()
}
}
}
[pscustomobject]@{
method = $method
provenance = $provenance
same = if ($before) {[object]::ReferenceEquals($before,($after = getSessionState $sb))}
before = if ($before) {'yes'}
after = if ($after) {'yes'}
}
}}
function getSessionState {
param($ScriptBlock)
[scriptblock].
GetProperty('SessionStateInternal',
[System.Reflection.BindingFlags] 'NonPublic, Instance').
GetValue($ScriptBlock)
}
$invoke = {
[CmdletBinding()]param(
$SubjectScriptBlock
)
$pipe = $SubjectScriptBlock.GetSteppablePipeline($MyInvocation.CommandOrigin,@())
$pipe.Begin($PSCmdlet)
$pipe.End()
}
$create = & $invoke ([scriptblock]::Create({ . { getSessionState {} }}))
$literal = & $invoke { . { getSessionState {} }}
$local = getSessionState {}
$module = getSessionState (. (New-Module {}) {{}})
'literal',
'local',
'module' |
? {$create -and
[object]::ReferenceEquals($create,
(Get-Variable $_ -ValueOnly))}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment