Last active
December 13, 2024 17:48
-
-
Save alx9r/c8f2062dcf82fa9b3f2527bd5aad52d9 to your computer and use it in GitHub Desktop.
Reference Code for https://stackoverflow.com/a/79279177/1404637
This file contains hidden or 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
| 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'} | |
| } | |
| }} |
This file contains hidden or 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
| 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