Created
August 30, 2025 05:39
-
-
Save romero126/41c6b59c5fffeabb34f05bee84339110 to your computer and use it in GitHub Desktop.
PostCommandLookupAction_CmdletInjection
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 script:Assert-PostCommandLookupAction_CmdletInjection { | |
| begin { | |
| Write-Host 'Proxy Command - Begin' | |
| } | |
| process { | |
| Write-Host 'Proxy Command - Process' | |
| } | |
| end { | |
| Write-Host 'Proxy Command - End' | |
| } | |
| } | |
| $ExecutionContext.InvokeCommand.PostCommandLookupAction = { | |
| param( | |
| $CommandName, | |
| $CommandLookupEventArgs | |
| ) | |
| # Right now we are only hooking Get-ChildItem | |
| # if ($CommandLookupEventArgs.ModuleName -ne '<My Module Name>') { | |
| # return | |
| # } | |
| if ($CommandName -ne 'Get-ChildItem') { | |
| return | |
| } | |
| # Generate a proxy command to standin for the origional command | |
| $proxyCommandMetaData = [System.Management.Automation.CommandMetaData]::new($CommandLookupEventArgs.Command) | |
| $proxyCommandScriptBlock = [System.Management.Automation.ProxyCommand]::create($proxyCommandMetaData) | |
| # We need to modify the proxyCommandScriptBlock to include logging information | |
| # Modify the proxyCommandScriptBlock to include Assert-PostCommandLookupAction_CmdletInjection code | |
| $postCommandLookupActionCommand_CmdletInjection = Get-Command -Name Assert-PostCommandLookupAction_CmdletInjection | |
| $proxyCommandScriptBlock = $proxyCommandScriptBlock -replace '\r' | |
| foreach ($astBlockKind in 'Begin', 'Process', 'End') { | |
| $astNamedBlock = $postCommandLookupActionCommand_CmdletInjection.ScriptBlock.ast.Find({ param($ast); $ast -is [System.Management.Automation.Language.NamedBlockAst] -and $ast.BlockKind -eq $astBlockKind }, $true) | |
| if (-not $astNamedBlock) { | |
| continue | |
| } | |
| $astBlockText = $astNamedBlock.Statements.Extent.Text | |
| $proxyCommandScriptBlock = $proxyCommandScriptBlock -replace "$astBlockKind`n{", "$astBlockKind`n{`n$astBlockText`n" | |
| } | |
| # Bind the proxyCommandScriptBlock to the lookup action and remove the command asserted. | |
| $CommandLookupEventArgs.Command = $null | |
| $CommandLookupEventArgs.CommandScriptBlock = [scriptblock]::Create($proxyCommandScriptBlock) | |
| $CommandLookupEventArgs.StopSearch = $true | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment