Automatically clear the host window before running new command

Quite often, before I figure out the final script, I try many single commands in the console window. After a while the screen gets clumsy.
I know the cls command is not a big deal but still it is repetitive task you need to do over and over. I’d like to automate it.
I tried to add the clear-host to my prompt function in the $profile. The trouble is the prompt function seems to be called after the cmdlet execution.
So the feedback like errors or output results is cleared.
Is there any way to run clear-host before execution of any new commands ?
This way I would always start with clean screen at the top.

Not really, no. I mean, I suppose you could do something along the lines of PSReadline and run a Clear-Host when you detect and end-of-line, but I’m not sure if you could get consistently good results that way.


I would like to suggest to change how you create and debug scripts. If you always start to create your scripts in the PowerShell ISE instead of the plain console and can run your single commands using the F8 (Run Selection) or blocks of commands. The overall experience should be better with many other advantages like syntax highlighting and Intellisense.


Thanks for the reply. I am almost there. I added the following code to my prompt fuction.

    $cmd  = Get-History -Count 1 | Select -Property CommandLine
    $cmd = [string]$cmd.CommandLine
    Invoke-Expression $cmd | Out-Host
    "$cmd`n" | Out-Host

It just works fine for me. It clear hosts, excecute the last command from the history then it displays my last command on the screen. :slight_smile:
The downside of the workaround it does not display the errors, verbose pipelines etc.

So the next step is how do I capture and redirect the other pipelines to the host ?

Thank you.


Yes, I use this approach too depending on the task I am working on.
The point is it does not prevent you from the clumsy console screen even in ISE editor.

Thank you.