Как очистить windows powershell

To clear the PowerShell console screen for a clean workspace, you can use the `Clear-Host` command, which removes all previous outputs displayed in the session.

Here’s how to do it:

Clear-Host

Understanding the Clear Command

What is the Clear Command in PowerShell?

The clear command in PowerShell is a built-in function that allows users to quickly refresh their console screen. By clearing the visible output, it creates a cleaner workspace, which is particularly helpful when you’ve executed multiple commands and wish to eliminate distractions from previous outputs. This aids in focusing on current tasks without clutter.

Why You Should Use Clear Command Regularly

Regularly utilizing the clear command enhances your command visibility and streamlines your workflow. A cluttered console can lead to confusion and mistakes, making it harder to interpret results or follow the sequence of executed commands. Using the clear command frequently maintains a clear focus on current operations, resulting in improved efficiency.

Clear PowerShell History: A Simple Guide

Clear PowerShell History: A Simple Guide

How to Use the Clear Command

Basic Syntax of the Clear Command

The clear command can be executed simply by typing:

Clear

This syntax is straightforward, allowing users to quickly refresh their console with minimal effort.

Using Clear to Refresh the Console

To clear the console, simply type the command at your PowerShell prompt and hit Enter. This action removes all currently displayed text, allowing you to start fresh. This is particularly handy during extended sessions where clutter can accumulate.

Keyboard Shortcuts for Clearing Console

In addition to typing the command, PowerShell also supports keyboard shortcuts. One of the most common is Ctrl + L, which clears the screen just as effectively and can save time. Mastering these shortcuts can enhance your productivity by minimizing repetitive typing.

Clear PowerShell Cache: A Simple Guide to Refreshing

Clear PowerShell Cache: A Simple Guide to Refreshing

Variations and Alternatives to Clear Command

Clearing the Screen vs. Clearing Output

It’s essential to distinguish between simply clearing the screen and clearing specific outputs. The clear command removes everything displayed in your current window. However, you might want to clear your PowerShell history selectively without disrupting your current session. Use the `Clear-Host` cmdlet if you want a specific command to reference:

Clear-Host

This command provides a clearer separation of functions, encouraging better command management.

Clearing Specific Buffers in PowerShell

In certain cases, you may want to target specific outputs rather than performing a blanket clear. There are commands that allow you to clear logs, caches, or specific buffers, facilitating a more fine-tuned control of what needs to be visible. By using filters or specific conditions, you can prevent losing valuable information when working with larger data sets.

BitLocker PowerShell: Unlocking Secrets Easily

BitLocker PowerShell: Unlocking Secrets Easily

Practical Examples of Clear Command in Action

Example 1: Basic Use Case

A typical scenario might involve running several commands to gather information. Let’s say you want to see the current processes running on your system. After executing your command, you might wish to clear the screen for better focus.

# Run some commands
Get-Process

# Clear the console
Clear

This example illustrates using the clear command to declutter your PowerShell window after executing commands.

Example 2: Scripting with Clear Command

Integrating the clear command into scripts helps enhance user experience. Imagine you create a script that loads data, and you want to inform the user while keeping the console clean for the final output:

# Sample script that uses the Clear command
Write-Host "Loading data, please wait..."
Start-Sleep -Seconds 2
Clear
Write-Host "Data has been successfully loaded!"

By clearing the console before displaying the final message, you ensure that users aren’t distracted by intermediate outputs.

Example 3: Combining Clear with Other Commands

The clear command can also be used in conjunction with other commands for better organization. Consider a scenario where you’re inspecting logs and want to avoid confusion after reviewing the output:

# Example with logging and clearing console
Get-EventLog -LogName Application
Clear

Using the clear command after reviewing the logs helps to maintain a focused perspective on subsequent commands.

Mastering Veeam PowerShell: A Quick Start Guide

Mastering Veeam PowerShell: A Quick Start Guide

Troubleshooting Common Issues with the Clear Command

Issues with Console Not Clearing

Sometimes, users may notice that the console does not clear as expected. This can occur due to certain settings or conditions in the environment. If you encounter this issue, ensure that you’re using the command in the correct context and check permissions related to your PowerShell session. Re-launching PowerShell is another simple troubleshooting step.

Understanding Limitations of the Clear Command

The clear powershell command has limitations. It cannot clear the command history or outputs from previous sessions; it only affects what is visible in the console window. If you encounter instances where the clear command doesn’t suit your needs, you might consider alternatives such as modifying the visibility settings or integrating other command-line tools.

Splat PowerShell: Mastering Command Shortcuts

Splat PowerShell: Mastering Command Shortcuts

Best Practices for Using the Clear Command

When to Use vs. When to Avoid

Adopt a mindful approach when using the clear powershell command. It’s beneficial to clear the console regularly during lengthy sessions, but overusing it might lead to confusion, especially if you need to track back through commands. Consider using it strategically—after significant outputs or before major tasks.

Incorporating Clear into Your Workflows

Leverage the clear command in your day-to-day workflows by making it a habit. Integrating it after high-volume outputs can help maintain a clean workspace. This reduces the distractions provided by previous commands, improving your overall efficiency.

Mastering the Art of Filter PowerShell Commands

Mastering the Art of Filter PowerShell Commands

Conclusion

Recap of the Importance of Clear Command

The clear powershell command serves as an essential tool for enhancing usability and clarity in your PowerShell sessions. Regularly implementing it into your routine can significantly boost your productivity.

Final Thoughts

Experiment with the clear command and related functionalities to discover what works best for your style of work. The cleaner your workspace, the clearer your focus.

Call to Action

We encourage readers to share their experiences using the clear powershell command. Join our community to explore more tips and tricks for mastering PowerShell and improving your efficiency.

Clearing the command history in PowerShell and Command Prompt is essential for improving readability, avoiding confusion, and maintaining privacy. Sometimes, we need to declutter the command window screen and start fresh. In this article, we’ll show you how to clear the command history screen in PowerShell and Command Prompt in Windows 10 and 11.

Before we learn the methods to clear the command screen in PowerShell, let’s check out the basics of command history. PowerShell keeps track of commands entered into the shell. This history of commands can be viewed and accessed in several ways.

  1. Up and down arrow keys: Pressing the up arrow key will cycle through your previously entered commands, allowing you to quickly access and reuse them.
  2. Get-History cmdlet: The Get-History cmdlet allows you to view a list of all the PowerShell commands used during your current session. This can be useful if you have to refer back to a specific command or if you want to see a list of all the commands you have entered so far.
  3. Invoke-History cmdlet: The Invoke-History cmdlet allows you to rerun a specific command from your command history without typing it out again. Using the ID number associated with the command in your history list will rerun the command with an ID of 23 from your history list.
    Example: Invoke-History -ID 23

Clearing the Command Screen in PowerShell

It is easy to clear the commands and their outputs in the current PowerShell session using PowerShell cmdlets (their aliases) and keyboard shortcuts.

Clear PowerShell Screen

Type the following cmdlet in PowerShell and hit Enter.

Clear-Host

clear host cmdlet in powershell window

This will clear the command window screen as shown below.

powershell command window screen cleared

Alternatively, you can use the aliases of the Clear-Host cmdlet to clear the PowerShell console. Simply type “cls“, “cls /?” or “clear” and hit Enter in the PowerShell window. This will remove all previous commands and outputs from the screen so that you start afresh with new tasks.

Moreover, you can also use keyboard shortcuts to clear the PowerShell screen in Windows 10 and 11. Pressing “Ctrl + L” on your keyboard will have the same effect as executing Clear-Host.

Clear PowerShell Command History

While Clear-Host clears the current console, the Clear-History cmdlet and Alt+F7 are used to clear the command history in PowerShell. If the PowerShell’s Clear-History is not working for you and it doesn’t clear the command history, it’s because PowerShell’s history is saved in a text file named ‘ConsoleHost_history.txt‘ at the following location.

C:\Users\user\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\

Use the following command to get the location of the command history text file in Windows 10 and 11.

(Get-PSReadlineOption).HistorySavePath

powershell command history text file location

You can either navigate to the above location on your PC and remove the contents of the ‘ConsoleHost_history.txt’ file, or execute the following command to clear the command history in PowerShell.

[Microsoft.PowerShell.PSConsoleReadLine]::ClearHistory()

You can also instruct PowerShell not to save the command history in the ‘ConsoleHost_history.txt’ at all.

Set-PSReadLineOption -HistorySaveStyle SaveNothing

To enable the saving of command history to the text file, use this command:

Set-PSReadLineOption -HistorySaveStyle SaveIncrementally

Clearing the CMD Screen and Command History

Clear Command Prompt Screen

You can clear a single line or everything from the Command Prompt screen and start with a clean slate.

To clear the Command Prompt screen on your Windows 10/11 PC, type cls or CLS in the command window, and press Enter.

use cls command to clear command prompt screen

Here are a few shortcut keys to help you while using the Command Prompt:

  • Esc or Escape: If you type a wrong command by mistake, you can quickly clear the line from the CMD window screen by pressing the Esc key.
  • Ctrl + Backspace: Deletes one left of the cursor.
  • Ctrl + C: Leave the line you are typing or terminate the command in process and start with a new prompt.
  • Alt+F4: Close an open PowerShell or Command Prompt window.

Clear the Command Prompt History

Command history is a useful feature in the Command Prompt. It allows you to access your past commands quickly and reuse them when needed. You can view the commands used in the current session in two ways:

  • Up and down arrow keys: Cycle through your previously entered commands.
  • F7: Shows the list of commands used in the CMD. You can use the up and down arrow keys to highlight the commands and press Enter to use them.
    use f7 to view command prompt history

If you want to clear the Command prompt history on Windows 10/11, press Alt+F7. That’s it! The command history will be cleared.

Using the “cls” command in Command Prompt and the “Clear-Host” cmdlet in PowerShell are simple ways to clear your screen and declutter your workspace. With these tips, you can effectively use clear screen commands and improve your productivity while working with PowerShell and Command Prompt.

Read Next: 3 Ways to Replace PowerShell with Command Prompt

Was this Article helpful?

YesNo

По-умолчанию в Windows, все команды, введенные в консоли PowerShell, сохраняются в текстовый лог-файл. Благодаря этому вы можете в любой момент повторно выполнить любую команду и просмотреть историю выполненных команд PowerShell даже после закрытия консоли или перезагрузки компьютера. В PowerShell сейчас используются два провайдера истории команда: история команд в текущей сессии (выводит командлет Get-History) и текстовый лог с предыдущими командами, которые сохраняет модуль PSReadLine.

Содержание:

  • Просмотр история команд в PowerShell
  • Поиск в истории команд PowerShell
  • Настройка истории команд PowerShell с помощью модуля PSReadLine
  • Как не сохранять определенные команды в историю PoweShell?
  • Использование Predictive IntelliSense для набора команд по истории
  • Очистка истории предыдущих команд в PowerShell
  • Импорт истории команд PowerShell в другую сессию

Просмотр история команд в PowerShell

Если нажать клавишу “вверх” в консоли PowerShell, перед вами появится последняя введенная вами команда. Если продолжить нажать клавишу «вверх» — вы увидите все команды, выполненные вами ранее. Таким образом с помощью клавиш «вверх» и «вниз» вы можете прокручивать историю команд PowerShell и повторно выполнять ранее набранные команды. Это удобно, если вам нужно быстро выполнить одну из предыдущих команд, не набирая ее заново.

Консоль PowerShell сохраняет полную историю команд, начиная с версии Windows PowerShell 5.1 (устанавливается по умолчанию начиная с Windows 10). В более ранних версиях Windows PowerShell (как и командная строка cmd) сохраняет историю выполненных команд только в текущей сессии PowerShell. Для просмотра истории предыдущих команд в текущей сессии используется командлет
Get-History
.

Чтобы вывести подробную информацию о ранее выполненных командах в текущей сессии PowerShell, в том числе время запуска/окончания команды:

Get-History | Format-List -Property *

get-history в powershell

Вы можете выполнить команду по ее ID:

Invoke-History 4

Если вы закрыли консоль PowerShell, то история команд сбрасывается и список в Get-History очищается.

Однако PowerShell 5.1 и PowerShell Core также сохраняют последние 4096 команд в тестовом файле в профиле каждого пользователя
%userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
.
Вы можете открыть этот файл и просмотреть историю команд в любом текстовом редакторе. Например, чтобы открыть файл с журналом команд с помощью блокнота:

notepad (Get-PSReadLineOption | select -ExpandProperty HistorySavePath)

файл ConsoleHost_history.txt с историей ранее выполненных команд powershell

История ведется отдельно для консоли PowerShell, отдельно для ISE.

Если команда PowerShell требует длительное время на выполнение, вы увидите ее в истории команд только по ее завершении.

В cmd вы можете вывести историю команд в текущей сессии с помощью:

doskey /history

Для поиска используется клавиша
F7
.

история команд в cmd - doskey /history

Поиск в истории команд PowerShell

Если вы не хотите пролистывать всю историю команд PowerShell, вы можете выполнить поиск по истории команд с помощью комбинаций клавиш CTRL+R (поиск в обратном направлении) и CTRL+S (поиск вперед). Нажмите сочетание клавиш и начните вводить часть команды, которую вы хотите найти в ранее выполненных командах. Выполняется поиск указанного текста на любой позиции в команде (в отличии от поиска в консоли PowerShell по F8 или Shift+F8, которые ищут совпадения только с начала строки). В консоли PowerShell должна появится предыдущая команда, соответствующая поисковой строке. Совпадения строки подсвечивается в команде.

Если найденная команда вас не устраивает, чтобы продолжить поиск по истории, нажмите сочетание
CTRL+R
/
CTRL+S
еще раз. В результате на экране появится следующая команда, соответствующая шаблону поиска.

поиск команды в истории powershell

С помощью клавиши
F8
можно найти в истории команду, соответствующую тексту в текущей командной строке. Например, наберите
get-
и нажмите
F8
. В истории будет найдена последняя команда, соответствующая строке. Чтобы перейти к следующей команде истории, нажмите F8 еще раз.

Также можно использовать символ
#
для поиска в истории команд. Например, чтобы найти последнюю команду, начинающуюся с
Get-WMI
, наберите
#get-wmi
и нажмите клавишу
Tab
. В консоли появится последняя команда, соответствующая шаблону:

Для вывода списка команд в истории, соответствующих запросу, можно использовать:

Get-History | Select-String -Pattern "Get-"

и

Get-Content (Get-PSReadlineOption).HistorySavePath| Select-String -Pattern "Get-"

поиск в комнадах Get-History | Select-String pattern

Настройка истории команд PowerShell с помощью модуля PSReadLine

Функционал хранения истории команд в PowerShell встроен не в сам Windows Management Framework, а основан на дополнительном модуле PSReadLine, который существенно расширяет функционал консоли PowerShell. Модуль PSReadLine в Windows находится в каталоге C:\Program Files\WindowsPowerShell\Modules\PSReadline и автоматически импортируется при запуске консоли PowerShell.

PSReadLine осуществляет подсветку синтаксиса в консоли, отвечает за возможность использования выделения текста мышкой и его копирование/вставку с помощью CTRL+C и CTRL+V.

Проверьте, что модуль загружен в вашу сессию PowerShell:

Get-Module

проверить что модуль psreadline установлен

Если модуль PSReadline не загружен, проверьте что он установлен и если нужно, установите его из онлайн репозитория PowerShell Gallery:

Get-Module -ListAvailable | where {$_.name -like "*PSReadline*"}

Install-Module PSReadLine

Полный список функций модуля PSReadLine для управления историей команд PowerShell и привязанных к ним клавишам можно вывести командой:

Get-PSReadlineKeyHandler | ? {$_.function -like '*hist*'}

Key       Function             Description
---       --------             -----------
Key       Function                Description
 ---       --------                -----------
UpArrow   PreviousHistory         Заменить введенные данные предыдущим элементом журнала
DownArrow NextHistory             Заменить введенные данные следующим элементом журнала
Ctrl+R    ReverseSearchHistory    Выполнить интерактивный поиск по журналу в обратном направлении
Ctrl+S    ForwardSearchHistory    Выполнить интерактивный поиск по журналу в направлении вперед
Alt+F7    ClearHistory            Удалить все элементы из журнала командной строки (не из журнала PowerShell)
F8        HistorySearchBackward   Искать предыдущий элемент журнала, который начинается с текущего ввода, например P...
Shift+F8  HistorySearchForward    Искать следующий элемент журнала, который начинается с текущего ввода, например Ne...
Unbound   ViSearchHistoryBackward Запускает новый поиск по журналу в направлении назад.
Unbound   BeginningOfHistory      Перейти к первому элементу журнала
Unbound   EndOfHistory            Перейти к последнему элементу (текущий ввод) в журнале

Get-PSReadlineKeyHandler

Выведите текущие настройки истории команд PowerShell модуля PSReadLine:

Get-PSReadlineOption | select HistoryNoDuplicates, MaximumHistoryCount, HistorySearchCursorMovesToEnd, HistorySearchCaseSensitive, HistorySavePath, HistorySaveStyle

Get-PSReadlineOption

Здесь могут быть интересны настройки следующих параметров:

  • HistoryNoDuplicates – нужно ли сохранять в истории PowerShell одинаковые команды;
  • MaximumHistoryCount – максимальное число сохраненных команд (по умолчанию сохраняются 4096 команд);
  • HistorySearchCursorMovesToEnd — нужно ли переходить в конец команды при поиске;
  • HistorySearchCaseSensitive – нужно ли учитывать регистр при выполнении поиска (по умолчанию при поиске в история команд регистр не учитывается);
  • HistorySavePath – путь к текстовому файлу, в который сохраняется история команд PowerShell;
  • HistorySaveStyle – особенности сохранения команд:
    • SaveIncrementally — команды сохраняются при выполнении (по-умолчанию)
    • SaveAtExit — сохранение истории при закрытии консоли
    • SaveNothing — не сохранять историю команд

Вы можете изменить настройки модуля PSReadLine с помощью команды Set-PSReadlineOption. Например, чтобы увеличить количество сохраняемых команд PowerShell в логе:

Set-PSReadlineOption -MaximumHistoryCount 10000

Если вам нужно, чтобы в историю команд PowerShell сохранялись не только выполненные команды, но и их вывод, вы можете настроить транскрибирование с помощью следующей функции. Просто добавьте ее в PowerShell профиль пользователя (notepad $profile.CurrentUserAllHosts):

Function StartTranscript {
Trap {
Continue
}
$TranScriptFolder = $($(Split-Path $profile) + '\TranscriptLog\')
if (!(Test-Path -Path $TranScriptFolder )) { New-Item -ItemType directory -Path $TranScriptFolder }
Start-Transcript -Append ($($TranScriptFolder + $(get-date -format 'yyyyMMdd-HHmmss') + '.txt')) -ErrorVariable Transcript -ErrorAction stop
}
StartTranscript

расширенный лого команда в консоли powershell

Теперь в профиле пользователя в каталоге
%USERPROFILE%\Documents\WindowsPowerShell\TranscriptLog
для каждого сенаса PowerShell будет содержаться подробный лог-файл.

Как не сохранять определенные команды в историю PoweShell?

В командной оболочке bash в Linux вы можете запретить сохранять в истории команды, которые начинаются с пробела (используется параметр HISTCONTROL= ignorespace). Вы можете настроить такое же поведение и для PowerShell.

Для этого, добавьте в PowerShell профиль текущего пользователя (
$profile.CurrentUserAllHosts
) следующий код:

Set-PSReadLineOption -AddToHistoryHandler {
    param($command)
    if ($command -like ' *') {
        return $false
    }
    return $true
} 

не сохранять определенные команды в историю powershellistoriyu

Теперь, если вы не хотите, чтобы ваша команда была сохранена в историю команд PowerShell, просто начните ее с пробела.

Также, начиная с версии модуля PSReadline v2.0.4, автоматически игнорируются и не сохраняются в историю команды, содержащие следующие ключевые слова: Password, Asplaintext, Token, Apikey, Secret. При этом вы можете командлеты из модуля управления паролями SecretManagement считаются безопасными и разрешены для сохранения.

Использование Predictive IntelliSense для набора команд по истории

В версии PSReadLine 2.2.2+ доступна новая функция PowerShell Predictive IntelliSense. Данная функция при наборе команды в консоли выводит наиболее подходящие команды из локальной истории команд.

В этом примере я набрал в консоли get-wm и функция Predictive IntelliSense предложила мне одну из команд, введенных ранее, которая соответствует моему вводу. Если эта команда мне подходит. Если меня устраивает эта команда, нужно нажать клавишу вправо чтобы принять эту команду и не набирать оставшиеся символы вручную.

Как использовать Predictive Intellisense в PowerShell

По умолчанию подсказки Predictive IntelliSense выводятся серым текстом и не очень хорошо читаются на черном фоне консоли PowerShell. Вы можете сделать текст подсказок более контрастным с помощью команды:

Set-PSReadLineOption -Colors @{ InlinePrediction = '#7A957A'}

Predictive IntelliSense по умолчанию включена начиная с PSReadLine 2.2.6. Чтобы включить ее вручную, выполните:

Set-PSReadLineOption -PredictionSource History

Чтобы сбросить предложение Predictive IntelliSense, нажмите Esc.

С помощью клавиши F2 можно переключиться в другое представление. Теперь вместо вывода одной наиболее подходящей команды (
InlineView
) будет выводится выпадающий список со всеми похожими командами (
ListView
).

список похожих команд в истории powershell

С помощью клавиш вверх/вниз вы можете быстро выбрать нужную команду из истории команд.

Predictive IntelliSense буте работать как в обычной командной строке pwsh.exe/powershell.exe, так и в Windows Terminal и Visual Studio Code.

Очистка истории предыдущих команд в PowerShell

Как мы рассказали выше, модуль PSReadline сохраняет все консольные команды PowerShell в текстовый файл. Однако в некоторых случаях администратору приходится вводить в консоли PowerShell различную конфиденциальную информацию (имена и пароли учетных записей, токены, адреса, и т.д.). Другой администратор сервера или атакующий может получить доступ к этим чувствительным данным в текстовом файле. В целях безопасности вы можете очистить журнал выполненных команд PowerShell или совсем отключить историю команд.

Командлет
Clear-History
позволяет очистить историю команд только в текущем сеансе PowerShell (очищается список предыдущих команд, которые выводит командлет Get-History).

Можно удалить из истории только одну предыдущую команду:

Clear-History -count 1 -newest

Или все команды по определенной маске:
Clear-History -CommandLine *set-ad*

Чтобы полностью удалить историю предыдущих команд PowerShell, нужно удалить текстовый файл, в который они сохраняются модулем PSReadline. Проще всего это сделать командой:

Remove-Item (Get-PSReadlineOption).HistorySavePath

После этого закройте сессию PoSh.
Чтобы полностью отключить ведение истории команд PowerShell, выполните команду:

Set-PSReadlineOption -HistorySaveStyle SaveNothing

очистить и отключить историю команд powershell

Импорт истории команд PowerShell в другую сессию

В некоторых случаях бывает удобно иметь под рукой один и тот же список часто-используемых команд PowerShell на различных компьютерах. Вы можете экспортировать текущую историю команд в xml файл и импортировать его на других компьютерах. Это можно сделать, скопировав файл ConsoleHost_history.txt в профиле пользователей на нужные компьютеры.
Также для экспорта команд из текущей сессии в файл можно использовать командлет
Export-Clixml
:

Get-History | Export-Clixml -Path c:\ps\commands_hist.xml

Для импорта команд из файла в другую сессию PoSh (на локальном или другом компьютере), выполните:

Add-History -InputObject (Import-Clixml -Path c:\ps\commands_hist.xml)

Add-History - импорт истории комманд powershell

Для автоматического импорта команд в файл при завершении сессии PoSh, можно привязать скрипт к событию завершения сессии PoSh (!! Сессия обязательно должна завершаться командной exit , а не простым закрытием окна PoSh):

$HistFile = Join-Path ([Environment]::GetFolderPath('UserProfile')).ps_history
Register-EngineEvent PowerShell.Exiting -Action { Get-History | Export-Clixml $HistFile } | out-null
if (Test-path $HistFile) { Import-Clixml $HistFile | Add-History }

Estimated Reading Time: < 1 min read


Table of Contents

  • Case
  • Solution

Case #

You have typed a lot of Powershell cmdlets and scripts and need to clean the Powershell command history in order to eradicate all instances of variables including passwords in clear text.

Solution #

Running Clear-History is not sufficient as this will not clear the running host’s command history. This command history is saved in a text file by using the Powershell PSReadLine module. PSReadLine maintains a history file containing all the commands and data you have entered from the command line. The history files is a file named $($host.Name)_history.txt. On Windows systems the history file is stored at $env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine. On non-Windows systems, the history files is stored at $env:XDG_DATA_HOME/powershell/PSReadLine or $env:HOME/.local/share/powershell/PSReadLine.

You will need to run the following commands to fully clear the Powershell command history:

Clear-History
Remove-Item "$env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\*"
Cloud School Docs - image 7 -

  1. Introduction to PowerShell Clear Screen

  2. Use the Clear-Host Command in PowerShell

  3. Conclusion

How to Clear the Screen in PowerShell

Usually, PowerShell users may experience the messy interface of the console as multiple commands do have various outputs. To get rid of such a situation, we need to clear the screen of the PowerShell console.

This article provides several ways to clear the PowerShell screen scripting environment.

Introduction to PowerShell Clear Screen

The PowerShell clear screen method is supported by the function Clear-Host and its two aliases, cls and clear. The plan of this section aims to guide you on clearing the PowerShell screen.

Use the Clear-Host Command in PowerShell

PowerShell automation depends on its native functions, cmdlets, and aliases supported by PowerShell. For example, Windows PowerShell’s Clean-Host command clears the screen of your console.

It’s a standalone operation of PowerShell that cannot be piped or used with any other cmdlet. It doesn’t generate output.

We can apply the Clear-Host function in the following way.

Aliases of Clear-Host Command in PowerShell

The aliases in PowerShell are associated with specific native commands. However, we can customize and create aliases for any function or a cmdlet in PowerShell.

For example, the Clear-Host function supports two built-in aliases, cls and clear.

In addition, one can clear the PowerShell’s console using the clear alias in the following way.

We can verify that these aliases use the Clear-Host function through the Get-Alias command.

Example Code:

Get-Alias clear
Get-Alias cls

Output:

PS C:\temp> Get-Alias Clear

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           clear -> Clear-Host

PS C:\temp> Get-Alias Cls

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           cls -> Clear-Host

We would have gone through the ways to clear the screen of PowerShell presented in the above section. However, it is observed that the PowerShell commands are not case sensitive, and the same applies to this function as well.

So, we can conclude that we can use the Clear-Host and its aliases in any letter case (upper or lower).

Conclusion

PowerShell is an innovative command-line tool with cross-platform support for all operating systems. Moreover, the said scripting language has many functions and cmdlets supported by aliases to perform multiple tasks.

In this article, we have presented how to clear the PowerShell screen.

The first method exercises the Clear-Host function to get a cleaner scripting console. The other two ways, Cls and Clear, are also associated with Clear-Host as they are aliases of Clear-Host.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Служба transmission для windows
  • Как уйти в спящий режим в windows 10 клавишами
  • Nvidia geforce gtx 560m driver windows 10
  • Отключить подписанные драйвера windows 7
  • Как проверить какая видеокарта на компьютере windows 10