Search code examples
powershellpowershell-3.0executioncontext

Can you access/modify parameters from a PostCommandLookupAction in powershell?


Hooking all instances of a command like cd and would like to verify and possibly modify input.

$executionContext.SessionState.InvokeCommand.PostCommandLookupAction = {
    param($CommandName, $CommandLookupEventArgs)
    #Only hook cd
    if($CommandLookupEventArgs.CommandOrigin -eq "Runspace" -and $CommandName -eq "cd"){
       //Do modification here
    }
}

Is there a variable that provides access to modify the parameters passed to cd?


Solution

  • If you specify the CommandScriptBlock the args will be available inside that scriptblock e.g.:

    $ExecutionContext.InvokeCommand.PostCommandLookupAction = {
        param($s,$ea) 
        if ($ea.commandname -eq 'cd') { 
            write-host "Intercpeting CD command"
            $ea.CommandScriptBlock = {Set-Location @args}
            $ea.StopSearch = $true
        } 
    }