Как посмотреть историю команд powershell
Перейти к содержимому

Как посмотреть историю команд powershell

  • автор:

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

date31.01.2023
useritpro
directoryPowerShell, Windows 10, Windows 11, Windows Server 2019
commentsкомментариев 6

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

Просмотр история команд в 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:

Если вы закрыли консоль 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 требует длительное время на выполнение, вы увидите ее в истории команд только по ее завершении.

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

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

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

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

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

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

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

powershell поиск в истории по F8

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

как найти ранее выполненную команду в истории powershell

winget install —id=Microsoft.PowerShell -e

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

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.

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

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

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

Get-Module -ListAvailable | where

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

Get-PSReadlineKeyHandler

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

Get-PSReadlineOption

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

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

  • 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 ) следующий код:

    не сохранять определенные команды в историю 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 -PredictionSource History

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

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

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

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

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

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

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

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

    Clear-History -count 1 -newest

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

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

    После этого закройте сессию 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)

    Предыдущая статьяПредыдущая статья Следующая статья Следующая статья

    Using Previous Command History in PowerShell Console

    By default, Windows saves all of the commands that you type in the PowerShell console to a text log file. This allows you to re-run any command and view the history of the PowerShell commands that you have run, even after you close the console or restart your computer. PowerShell currently uses two command history providers: the history of commands in the current session (displayed by the Get-History cmdlet) and a text log with previous commands that the PSReadLine module saves.

    Viewing PowerShell Command History on Windows

    In the PowerShell console, the last command you typed appears when you press the Up key. If you continue to press the “up” key, you will see all the commands executed earlier. Thus, using the “ Up arrow ” and “ Down arrow ” keys you can scroll through the history of PowerShell commands and re-run previously typed commands. This is useful if you need to quickly execute one of the previous commands without typing it again.

    The PowerShell console keeps a complete command history since Windows PowerShell 5.1 (installed by default in Windows 10). In previous versions of Windows PowerShell (and the cmd command prompt), the history of executed commands is available only in the current PowerShell session. Use the Get-History cmdlet to view the history of previous commands in the current session.

    You can display more detailed information about previously executed commands in the current PowerShell session, including the command status and start/end/duration time:

    Get-History | Format-List -Property *

    powershell get-history

    You can run the previous command by its ID:

    The command history is reset and the list in Get-History is cleared when you close the PowerShell console.

    However, Windows PowerShell 5.1 and PowerShell Core also save the last 4096 commands in a plain text file in each user’s profile %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt .

    You can open this file and view the command history using any text editor. For example, to open a command log file using Notepad:

    notepad (Get-PSReadLineOption | select -ExpandProperty HistorySavePath)

    powershell view consolehost-history log file

    The history log is kept separately for the PowerShell console and for PowerShell ISE.

    The F7 key is used to search through cmd history.

    cmd list commands - doskey /history

    How to Search in PowerShell Command History?

    If you don’t want to scroll through the entire PowerShell command history using up/down arrows, you can search the command history by using the keyboard shortcuts CTRL+R (reverse search) and CTR +S (forward search). Press the key combination and start typing part of the command that you want to find in previously executed commands. The text you entered will be found in the command history in any position (unlike search in PowerShell using F8 or Shift+F8 , which allows looking for the matches from the beginning of the line only). The PowerShell console should display the previous command corresponding to the search string. Line matches are highlighted in the command.

    Press CTRL+R / CTRL+S again to continue searching the history if the found command is not what you want. As a result, the following command corresponding to the search pattern will appear on the screen.

    powershell command history bck-i-search

    Using the F8 key, you can search for the command in history that matches the text on the current command line. For example, type get- and press F8 . The last entry in the command history matching this text will be found. To go to the next command in history, press F8 again.

    how to search powershell command history

    You can also use the # character to search through the command history. For example, to find the last command that starts with Get-WMI, type #get-wmi and press the Tab key. The last command matching the pattern will appear in the console:

    search commands in powershell history

    winget install —id=Microsoft.PowerShell -e

    To display a list of commands in history that match a query, you can use:

    Get-History | Select-String -Pattern «Get-«

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

    powershell Get-History Select-String Pattern

    Configure PowerShell Command History with the PSReadLine Module

    The command history functionality in PowerShell is not built into the Windows Management Framework itself but is based on the PSReadLine module, which greatly enhances the functionality of the PowerShell console. The PSReadLine module on Windows is located in C:\Program Files\WindowsPowerShell\Modules\PSReadline folder and is automatically imported when you start the PowerShell console.

    Check that the module is loaded into your current PowerShell session:

    Check that the module is loaded into your current PowerShell session: Get-Module

    If the PSReadline module is not loaded, verify that it is installed. If necessary, install it from the PowerShell Gallery online repository:

    Get-Module -ListAvailable | where

    A complete list of functions of the PSReadLine module for managing the commands history in PowerShell and the keys assigned to them can be displayed with the command:

    Get-PSReadlineKeyHandler

    List the current PowerShell command history settings in the PSReadLine module:

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

    Get-PSReadlineOption

    You may want to consider the following PSReadline parameters:

    • HistoryNoDuplicates – whether the same commands have to be saved;
    • MaximumHistoryCount – the maximum number of the stored commands (by default the last 4096 commands are saved);
    • HistorySearchCursorMovesToEnd — whether it is necessary to jump to the end of the command when searching;
    • istorySearchCaseSensitive – whether a search is case sensitive (PowerShell command history is not case sensitive by default);
    • HistorySavePath – path to a text file where the history of PowerShell commands is stored;;
    • HistorySaveStyle – command history saving options:
      • SaveIncrementally — the commands are saved when executed (by default);
      • SaveAtExitthe history is saved when you close the PowerShell console;
      • SaveNothing — disable saving command history.

      You can change the PSReadLine module settings with the Set-PSReadlineOption command. For example, to increase the number of PowerShell commands stored in the log:

      Set-PSReadlineOption -MaximumHistoryCount 10000

      If you want to save not only the executed commands but also their output in the PowerShell command history, you can enable command transcription. Just add the following function to the user’s PowerShell profile ( 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

      Enable PowerShell History with detailed Transcript

      The user profile now contains a detailed log file for each PowerShell session in the %USERPROFILE%\Documents\WindowsPowerShell\TranscriptLog directory.

      How to Run a PowerShell Command without Saving it to History?

      In the Linux bash shell, you can disable history for commands starting with spaces (with HISTCONTROL= ignorespace ). You can configure similar behavior for PowerShell.

      To do this, add the following code to the current user’s PowerShell profile ( $profile.CurrentUserAllHosts ):

      dont save command with front space to powershell history

      Now, just start your command with a space if you don’t want it to be saved in the PowerShell command history.

      Also, starting with the Readline v2.0.4 module version, commands containing the following keywords are automatically ignored and not saved to the history: Password , Asplaintext , Token , Apikey , Secret . At the same time, cmdlets from the SecretManagement password management module are considered safe and allowed to be saved to the history file.

      Using Predictive IntelliSense with PowerShell Command History

      A new PowerShell Predictive IntelliSense feature is available in PSReadLine 2.2.2+. This feature displays the most appropriate commands from the local command history when you type a command in the PowerShell console.

      In this example, I typed get-wm in the console, and Predictive IntelliSense suggested one of the commands I typed earlier that matched my input. If this command suits me, I need to press the right arrow key to accept this command and not type the rest of the characters manually.

      Using PowerShell Predictive Intellisense

      By default, Predictive IntelliSense hints are displayed in gray text and are difficult to read against the black background of the PowerShell console. This command makes the suggested text more contrasting:

      Set-PSReadLineOption -PredictionSource History

      To reset the IntelliSense predictive suggestion, press the Esc key.

      You can switch to another view by pressing the F2 key. Now, instead of displaying one most appropriate command ( InlineView ), a drop-down list with all similar commands will be displayed ( ListView ).

      Lixt Predictive IntelliSense command suggestions from PowerShell history

      Use the up/down keys to quickly select a command you need from the command history.

      How to Clear the Command History in PowerShell?

      As we explained above, the PSReadline module saves all PowerShell console commands to a text file. However, in some cases, the administrator has to enter various sensitive information into the PowerShell console (credentials, passwords, tokens, addresses, personal data, etc.). History data in a plain text file can be accessed by another server administrator or attacker. For security reasons, you might have to clear the history of the PowerShell commands that you have run or turn off the command history completely.

      The Clear-History cmdlet allows you to clear the history of commands only in the current PowerShell session. It only deletes the previous command list that Get-History returns.

      You can remove only one previous command from the history:

      Clear-History -count 1 -newest

      Or clear all commands with a specific pattern:

      Clear-History -CommandLine *set-ad*

      To completely clear the history of previous PowerShell commands, you need to delete the ConsoleHost_history.txt file that the PSReadline module writes to. You can get the current PowerShell history file location and remove it with the command:

      After that, close the PowerShell console window.

      If you want to completely disable saving the history of PowerShell commands to a text file, run the command:

      Set-PSReadlineOption -HistorySaveStyle SaveNothing

      disable powershell comand history

      How to Export/Import PowerShell Command History to Another Session?

      Sometimes it is convenient to have the same set of frequently used PowerShell commands on different computers. You can export the current command history on your computer to an XML file and import it to other computers. You can do this by copying the ConsoleHost_history.txt file in the user’s profile to the target computers.

      You can also use the Export-Clixml cmdlet

      to export command history from the current session to a text file:

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

      To import command history from a file into another PowerShell session (on a local computer or on a different computer):

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

      export import powershell history

      To automatically export the previous commands to a file when the PowerShell session ends, you can bind the script to the PoSh session end event (!! The session must be terminated with the exit command, r, not by simply closing the PowerShell console):

      How can I see the command history across all PowerShell sessions in Windows Server 2016?

      Where can you view the full history from all sessions in Windows Server 2016?

      The following PowerShell command only includes the commands from the current session:

      Peter Mortensen's user avatar

      Daniel Leach's user avatar

      7 Answers 7

      In PowerShell enter the following command:

      This gives you the path where all of the history is saved. Then open the path in a text editor.

      Try cat (Get-PSReadlineOption).HistorySavePath to list the history in PowerShell.

      Peter Mortensen's user avatar

      Daniel Leach's user avatar

      For getting full history from PowerShell and save the output to file I use this command:

      BogdanPopa's user avatar

      Since you are on windows you can also use below to open ‘notepad’ with it.

      On windows PowerShell

      To get in a session you can use h or history

      but to get all commands written in the computer you use

      Codertjay's user avatar

      There’s mention of Windows Server/Enterprise editions, but as a Pro (standard retail version) user HistorySavePath is also available to me. I needed to see what python packages were recently installed in an older session and wanted to add an answer here for people looking for specific things in the history.

      In my case I ran

      which gave me a list of pip install commands run from my previous sessions

      Also in Psreadline, you can search the saved history backwards with either f8 (after typing something on the command line) or control-R. Get-psreadlinekeyhandler lists the key bindings.

      How to Use PowerShell History Feature

      Download a free trial of Veeam Backup for Microsoft 365 and eliminate the risk of losing access and control over your data!

      Table of Contents

      Have you forgotten a command while in the command-line, or do you wish you had saved history, PowerShell history to the rescue!

      Not a reader? Watch this related video tutorial!

      In this tutorial, learn how to run prior commands, import and export, and clear history. By the end of the article, you won’t have to rely solely on the up and down arrow keys to retrieve history anymore!

      Prerequisites

      To follow along with this tutorial, be sure you Windows PowerShell on Windows 10 or PowerShell 7.x on any supported platform.

      Retrieving Command History

      If you have ever lost a command, you may want to save it to find later. If so, PowerShell saves time by saving your history for quick retrieval. To see your saved history, PowerShell has the Get-History cmdlet.

      Before retrieving any history, you first need to build some, as the history is restarted on every console session. To do so, copy and run the code below to add history entries; any code will do. Commands need to exist before Get-History has anything to return!

      Now that you have run some commands, as shown below, you have history to work with.

      Building PowerShell command history.

      Building PowerShell command history.

      Be mindful of sensitive commands that may contain info not meant for prying eyes. For example, if you do not use secure strings in your code, sensitive information such as a password or API secret will be visible as plain text in the history file!

      Now use the Clear-Host command to tidy up the screen and further demonstrate the history features.

      Clearing the screen doesn’t mean that all history entries are gone. To find the commands previously cleared, hit the up ↑ or down ↓ arrows to quickly view the console hosts’ command history.

      Using the up and down arrows is great when finding a single command you ran previously. But what about re-running more than one command? In that case, to display your full session history, type in the Get-History command as seen below, which presents a list of previously run commands.

      As shown below, Get-History returns not only the commands that were run but also a command ID and how long that command took to execute. The command ID will come in handy later.

      The maximum default history entries are 4096 as stored in the MaximumHistoryCount variable. Change this value to allow up to 32767 entries with the command: Set-Variable MaximumHistoryCount 32767 .

      By default, the Get-History cmdlet doesn’t return all object properties. To return all object properties, pipe the history output to the Select-Object cmdlet. Piping the output to the Select-Object cmdlet returns the StartExecutionTime and EndExecutionTime properties and are referenced to determine the Duration .

      Running Previously Executed Commands

      Now that you can retrieve older commands, what good is that? Most of the time, PowerShell users need to execute those commands. Luckily, you can do so without copying/pasting. Remembering a previous command or series of commands may be difficult. To run a previous command, execute the Invoke-History cmdlet.

      If you have been following along, you will have a previous Get-Service command in your history. As mentioned earlier, each history entry has an associated ID .

      Perhaps you need to re-run one of the Get-Service commands you ran earlier. In that case, copy and run the code below to re-run the second history entry, as shown in the below demonstration.

      Your ID value may need to change depending on your personal command history.

      Specifying a value of 2 for the ID parameter, the Invoke-History cmdlet immediately re-runs the command as if you had typed the command directly into the console.

      In addition to a number, the ID parameter also accepts a pattern to match against. For example, running Invoke-History -Id ‘Get-Service’ will find all history entries starting with that value.

      Exporting PowerShell Command History

      After a long work session, you may want to save and export your commands. If so, you’re in luck. PowerShell can export nearly anything to a text file; command history is no different. When working with command history, common formats include CSV or XML.

      Save your PowerShell history for future use, as shown below. Piping Get-History to the Export-CSV cmdlet allows you to save the history entries to a file. In this example, PowerShell saves the file to C:\Temp, but you can save the command history anywhere.

      Exporting command history.

      Exporting command history.

      To export the history as XML: Get-History | Export-CliXml -Path ‘C:\Temp\CommandHistory.xml’

      Clearing Command History

      Over time your history may become cluttered or you may have run a command with a sensitive value that is now saved to history. In either case, you probably want to remove those entries from your command history. To do that, to clear the console history, with the Clear-History cmdlet.

      By default, the Clear-History command removes all console history. But, what if you don’t want to delete all history? In that case, selectively clear history with a specific entry ID , a specified Count of entries, or only the Newest set of entries.

      If you don’t want to type in or locate a specific set of entries, pass an array of wildcard patterns to the CommandLine parameter to remove all matched commands.

      There is another type of history, which is saved to disk via the PSReadLine module. The Clear-History cmdlet only clears the current in-memory console history, but you may also want to clear all saved disk history entries.

      To clear all history except for the last run command, use the PSReadline method by running: [Microsoft.PowerShell.PSConsoleReadLine]::ClearHistory()

      Before clearing the disk history, you must find where it is saved. To do that, copy and run the following command to retrieve the history file disk location.

      Locating the history file save path.

      Locating the history file save path.

      The default PSReadLine Windows path is stored in the HistorySavePath variable and is: %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt

      Now open the history file in notepad, similar to what is shown below. Each history entry is added below the last saved command.

      History File in Notepad

      History File in Notepad

      Now that you have seen where and what is in the history file, remove the history file with the Remove-Item cmdlet, as shown below.

      Removing the history file.

      Removing the history file.

      Upon running another command, the history file will be regenerated.

      Importing Command History

      If you have opened a new console session or have previously saved a complicated series of commands, you may want to import them into your current history. To import those commands into your current console history, leverage the Add-History command.

      To import prior history, you first need an exported history file. In a previous section, you saved a series of commands in a CSV file, and perhaps you need to import those saved commands. To import the previous CSV file and add history entries to the current session, run the below code, adjusting your CSV path as necessary.

      As shown below, PowerShell imported the previous commands into console history and displayed them with the PassThru parameter.

      Not all commands return the original objects passed in. By adding the PassThru parameter, available on some cmdlets, the original object is returned.

      Importing exported PowerShell command history.

      Importing exported PowerShell command history.

      Considering Security and PowerShell History

      Despite the usefulness of PowerShell history, there are security considerations to be aware of. You will want to be mindful when entering sensitive commands, as those commands are saved to the plaintext command history file, subject to scrutiny.

      Pretend for a moment you are a ‘Red Teamer‘. You want to do some recon on a target user. You may be interested in commands they run, passwords and API keys they may be passing through the session during a normal day.

      Here’s a sample of what you could see looking at a target’s history file in real time, by just reloading the text file in Notepad++:

      Reloading Text File in Notepad

      Reloading Text File in Notepad

      Now you have a password that the target is using. Just watching the rest of the session history and you’ll more than likely see where that password is being used.

      Don’t be alarmed by what you’ve seen. Knowing what you know now, you can make better decisions.

      How do you securely handle secrets? By retrieving credentials from disk or keyboard input with the Get-Credential cmdlet. Secure those API keys and other secrets by converting to a secure string with the ConvertTo-SecureString cmdlet. Both cmdlets will not display the secret itself in history. PowerShell Secrets Management is also a good choice.

      In any environment, turning on ScriptBlock and Module logging is prudent. With this logging, PowerShell is a poor choice for an attacker to use, as every run of code is stored for later retrieval.

      What’s Next?

      You should now know how the PowerShell history commands work. Now the next time you lose an important command or need to save your session’s history, you have no excuse!

      If you need to clear all history except for the last run command, use the PSReadline method by running

      Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

      More from ATA Learning & Partners

      Recommended Resources!

      Recommended Resources for Training, Information Security, Automation, and more!

      Get Paid to Write!

      ATA Learning is always seeking instructors of all experience levels. Regardless if you’re a junior admin or system architect, you have something to share. Why not write on a platform with an existing audience and share your knowledge with the world?

      ATA Learning Guidebooks

      ATA Learning is known for its high-quality written tutorials in the form of blog posts. Support ATA Learning with ATA Guidebook PDF eBooks available offline and with no ads!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *