Windows powershell история команд

Previous Command History in PowerShell Console

By default Windows PowerShell (as well as the command prompt) saves the history of executed commands only in the current PowerShell session. When you close the PowerShell console window or restart your computer, the history of the PowerShell commands that you typed is not saved anywhere. Compared with the bash, this is a significant drawback. Starting with PowerShell 5.0 introduced in Windows 10 (Windows Server 2016), all commands entered in the PS console are now saved to a plain text log file by default.

Command History in PowerShell 5.0 and Newer

Suppose you typed and executed some complex PowerShell command. In Windows 10 and Windows Server 2016, even after restarting the computer, you can open a new PowerShell session and press the up arrow key. The last command you entered should be displayed on the screen. If you continue to press the “up” key, you will see all the commands executed earlier. Thus, using the keys “ Up arrow ” and “ Down arrow ” you can scroll through the history of PoSh commands and re-execute previously typed commands.

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 *

By default, the PowerShell in Windows 10 saves the last 4096 commands that are stored in a plain text file located in the profile of each user %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt .

The history is stored separately for PowerShell and PowerShell ISE.

If a PowerShell command takes a long time to execute, you will only see it in the command history when it completes.

The F7 key is used to search through cmd history.

How to Search 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 to look 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.

If the found command doesn’t suit you, to continue searching through the history, press CTRL+R / CTRL+S again. As a result, the following command corresponding to the search pattern will appear on the screen.

Using the F8 key, you can find the command in history that matches the text on the current command line. For example, enter 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.

Читайте также:  Как посмотреть содержимое диска с windows 10

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:

To get a list of previous PoSh command in the Notepad.exe window, run the command:

notepad (Get-PSReadLineOption | select -ExpandProperty HistorySavePath)

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

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

Managing PowerShell Command History with the PSReadLine Module

The command history functionality in PowerShell 5.0 is not built into the Windows Management Framework itself, but is based on the third-party PSReadLine module, which significantly extends the functionality of the PowerShell console. PSReadLine highlights the syntax in the console, it is responsible for selection of the text with your mouse and copying/pasting it using CTRL+C and CTRL+V . This module in Windows 10 is located in the C:\Program Files\WindowsPowerShell\Modules\PSReadline folder and is automatically imported when the PowerShell console starts.

PSReadLine is not included into the standalone PowerShell 5.0 (or never) installer for previous versions of Windows. Thus, if you want to use the PowerShell command history functionality in previous Windows versions (Windows 7/8.1 and Windows Server 2008R2/2012R2), in addition to installing Windows Management Framework 5.1, you will need to install the PSReadLine module via the PackageManagement module (formerly OneGet) from the online repository using the command:

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:

The command history can be configured using Get-PSReadlineOption and Set-PSReadlineOption cmdlets. Current PSReadline settings can be viewed using this command:

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

The settings of the following PSReadline parameters can be important for us:

  • HistoryNoDuplicates – determines 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 — determines whether you have to go to the end of the command when searching;
  • HistorySearchCaseSensitive – determines whether search is case sensitive (PS command history is not case sensitive by default);
  • HistorySavePath – shows the path to the file in which the command is stored;
  • HistorySaveStyle – determines the peculiarities of saving commands:
    • SaveIncrementally — the commands are saved after they are run (by default);
    • SaveAtExit the history is saved when the PowerShell console is closed;
    • SaveNothing — disable saving command history.

You can change the settings of PSReadLine module using the Set-PSReadlineOption. For example:

Set-PSReadlineOption -HistorySaveStyle SaveAtExit

To increase the number of PowerShell commands saved in the log file, run the command:

Set-PSReadlineOption -MaximumHistoryCount 10000

So, the ability to save the history of executed PowerShell commands is one of the arguments to prefer PoSh console to cmd.

How to Clear PowerShell Console History Commands?

As we explained above, the PSReadline module saves all the PowerShell console commands to a text file. However, in some cases, the administrator has to enter various sensitive information in the PowerShell console (credentials, passwords, addresses, personal data, etc.). Thus, another server administrator or attacker can access the history data in a plain text file. For security reasons, you might need to clear the history of the executed PowerShell commands or completely disable the command history.

The Clear-History cmdlet can only be used to clear the in-memory command history of the current PowerShell session. It clears only the list of previous commands that the Get-History cmdlet displays.

Читайте также:  Как установить windows server 2012 r2 с диска

You can remove only one previous command from 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 to which they are written by the PSReadline module. 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 PowerShellcommands to a text file, run the command:

Set-PSReadlineOption -HistorySaveStyle SaveNothing

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. Also this can be done by copying the ConsoleHost_history.txt file to user profiles on the desired computers.

To export commands from the current session to a file, you can use the Export-Clixml cmdlet:

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

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

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

To automatically export the previous commands to a file at the end of a PowerShell session, you can bind the script to the PoSh session termination event (!! The session must be necessarily ended with the exit command, rather than simply closing the PowerShell window):

Как в Powershell History смотреть и использовать историю команд

15 августа 2019

History — командлет, который возвращает в powershell историю команд аналогично Linux. Мы так же можем вызвать команду из истории, экспортировать и импортировать.

Что бы увидеть все команды по работе с историей выполните:

Вся история хранится в рамках текущей сессии и поэтому, если вы закрыли окно Powershell, вся история будет потеряна.

У Get-History есть алиас history, так что можно использовать что вам удобнее.

С помощью этого командлета мы получим всю историю:

У нас доступно два параметра:

  • id — получение команды по идентификатору
  • Count — число последних команд, которые должны вернуться

Следующий командлет исполнит команду по её id:

Вместо ID можно написать и часть команды, но исполнится именно та, которая употреблялась чаще всего:

Если сомневаетесь какая команда выполнится, то можете использовать ключ WhatIF, который сэмулирует действия без каких либо изменений.

Если у нас целый ряд команд, который мы хотим выполнить, то можно просто передать их через цикл. В моем случае это команделты с 162 по 166:

Мы можем выгрузить данные в csv с Powershell:

Как работать с WMI в Powershell

Затем импортировать и добавить в историю команды:

Отмечу, что команды импортируются под другими номерами.

Для очистки истории:

Очистить историю можно по:

  • id — по идентификатору
  • CommandLine — по точному соответствию команд
  • Count — определенное число
  • Newest — самые последние

Кроме этого, при получении истории у нас так же есть данные по времени запуска и окончании работы команд:

Get-History

Gets a list of the commands entered during the current session.

Syntax

Description

The Get-History cmdlet gets the session history, that is, the list of commands entered during the current session.

PowerShell automatically maintains a history of each session. The number of entries in the session history is determined by the value of the $MaximumHistoryCount preference variable. Beginning in Windows PowerShell 3.0, the default value is 4096 . By default, history files are saved in the home directory, but you can save the file in any location. For more information about the history features in PowerShell, see about_History.

Читайте также:  Сортировка строк по длине linux

The session history is managed separately from the history maintained by the PSReadLine module. Both histories are available in sessions where PSReadLine is loaded. This cmdlet only works with the session history. For more information see, about_PSReadLine.

Examples

Example 1: Get the session history

This example gets the entries in the session history. The default display shows each command and its ID, which indicates the order in which they ran.

Example 2: Get entries that include a string

This example gets entries in the command history that include the string service. The first command gets all entries in the session history. The pipeline operator ( | ) passes the results to the Where-Object cmdlet, which selects only the commands that include service.

Example 3: Export history entries up to a specific ID

This example gets the five most recent history entries ending with entry 7. The pipeline operator passes the result to the Export-Csv cmdlet, which formats the history as comma-separated text and saves it in the History.csv file. The file includes the data that is displayed when you format the history as a list. This includes the status and start and end times of the command.

Example 4: Display the most recent command

This example gets the last command in the command history. The last command is the most recently entered command. This command uses the Count parameter to display just one command. By default, Get-History gets the most recent commands. This command can be abbreviated to «h -c 1» and is equivalent to pressing the up-arrow key.

Example 5: Display all the properties of the entries in the history

This example displays all of the properties of entries in the session history. The pipeline operator passes the results of a Get-History command to the Format-List cmdlet, which displays all of the properties of each history entry. This includes the ID, status, and start and end times of the command.

Parameters

Specifies the number of the most recent history entries that this cmdlet gets. By, default, Get-History gets all entries in the session history. If you use both the Count and Id parameters in a command, the display ends with the command that is specified by the Id parameter.

In Windows PowerShell 2.0, by default, Get-History gets the 32 most recent entries.

Type: Int32
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False

Specifies an array of the IDs of entries in the session history. Get-History gets only specified entries. If you use both the Id and Count parameters in a command, Get-History gets the most recent entries ending with the entry specified by the Id parameter.

Type: Int64 [ ]
Position: 0
Default value: None
Accept pipeline input: True
Accept wildcard characters: False

Inputs

You can pipe a history ID to this cmdlet.

Outputs

This cmdlet returns a history object for each history item that it gets.

Notes

The session history is a list of the commands entered during the session. The session history represents the run order, the status, and the start and end times of the command. As you enter each command, PowerShell adds it to the history so that you can reuse it. For more information about the command history, see about_History.

Starting in Windows PowerShell 3.0, the default value of the $MaximumHistoryCount preference variable is 4096 . In Windows PowerShell 2.0, the default value is 64 . For more information about the $MaximumHistoryCount variable, see about_Preference_Variables.

Оцените статью