Windows – hook PowerShell to call a function each time I execute a command

consolepowershellwindows

I want to change the title of the PowerShell window to the command line of the currently executing process inside it, just like CMD.EXE does.

Can I do this in PowerShell?

Is there some function like prompt which is called when I execute a command in PowerSHell?

Best Answer

Do you want it for a small select number of executables? Or all exes?

One hack for a select number of executables would to do

function cmd
{
    $title = $host.UI.RawUI.WindowTitle
    $host.UI.RawUI.WindowTitle = 'cmd.exe ' + ($args -join " ")
    cmd.exe $args
    $host.UI.RawUI.WindowTitle = $title
}

Then just run cd c: cmd /c dir /s

And see the title change

And for all the commands

Get-Command -CommandType Application | where {$_.Name -match '.exe$'} | %{
$f = @'
    function {0}
    {{
        $title = $host.UI.RawUI.WindowTitle
        $host.UI.RawUI.WindowTitle = '{0} ' + ($args -join " ")
        {0}.exe $args
        $host.UI.RawUI.WindowTitle = $title
    }}
'@ -f ($_ -replace '.exe', '')
Invoke-Expression $f
}

And then try ping 127.0.0.1

Its hacky, YMMV