Automatically clear the host window before running new command

Welcome Forums General PowerShell Q&A Automatically clear the host window before running new command

This topic contains 4 replies, has 3 voices, and was last updated by

 
Participant
4 years, 4 months ago.

  • Author
    Posts
  • #17746

    Participant
    Points: 0
    Rank: Member

    Hello,
    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.
    Tomasz

  • #17748

    Keymaster
    Points: 1,673
    Helping HandTeam Member
    Rank: Community Hero

    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.

    • #17755

      Participant
      Points: 0
      Rank: Member

      Don,

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

          cls
          $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. 🙂
      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.
      Tomasz

  • #17749

    Moderator
    Points: 24
    Team Member
    Rank: Member

    Tomasz,

    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.

    • #17756

      Participant
      Points: 0
      Rank: Member

      Daniel,

      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.
      Tomasz

The topic ‘Automatically clear the host window before running new command’ is closed to new replies.