Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save romero126/41c6b59c5fffeabb34f05bee84339110 to your computer and use it in GitHub Desktop.

Select an option

Save romero126/41c6b59c5fffeabb34f05bee84339110 to your computer and use it in GitHub Desktop.
PostCommandLookupAction_CmdletInjection
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