Clear-Host

Exploring the Clear-Host Cmdlet in PowerShell

Welcome back to Wahmans Powershell Blog! Today we’re taking a look at one of the simplest but surprisingly helpful cmdlets in PowerShell: Clear-Host.

Cmdlet: Clear-Host
Description from Microsoft: Clears the display in the host program.

This cmdlet is primarily used to clear the screen in your PowerShell session, it’s useful for improving readability, especially when working interactively or running scripts with lots of output.

Examples of Using Clear-Host

1. Basic Use – Clear the Terminal Screen

This is the simplest use of Clear-Host, simply type it into your session to clear your console window.

Clear-Host

2. Assign a Shortcut

Want to use a shortcut for Clear-Host? You can create a function or alias in your profile.

# Add to your PowerShell profile
function cls { Clear-Host }

After this, typing cls will behave the same as Clear-Host, just like in CMD!

3. Use in a Script for Better Output Segmentation

If your script produces a lot of information but you want to separate different sections, Clear-Host can help increase clarity.

# Sample script segment
"Generating system report..."
Start-Sleep -Seconds 3
Clear-Host
"Loading next report section..."

4. Advanced: Use with UI Prompting and Loops

Here’s a more advanced example where Clear-Host enhances user interaction:

do {
    Clear-Host
    Write-Host "Select an option:"
    Write-Host "1. Say Hello"
    Write-Host "2. Show Date"
    Write-Host "3. Exit"
    $input = Read-Host "Enter your choice"

    switch ($input) {
        "1" { Write-Host "Hello there!"; Start-Sleep 2 }
        "2" { Get-Date; Start-Sleep 2 }
    }
} while ($input -ne "3")

This loop clears the screen with each iteration to keep the interface clean and user-friendly.

Conclusion:
While Clear-Host may seem trivial at first glance, it proves to be a valuable tool for usability and polish in scripts and modules. From simple screen clearing to interactive menu systems, it deserves a spot in every PowerShell user’s toolkit.

Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *