当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 在 PowerShell 控制台中使用以前的命令历史记录

作者:精品下载站 日期:2024-12-15 00:46:30 浏览:17 分类:玩电脑

在 PowerShell 控制台中使用以前的命令历史记录


默认情况下,Windows 会将您在 PowerShell 控制台中键入的所有命令保存到文本日志文件中。这允许您重新运行任何命令并查看已运行的 PowerShell 命令的历史记录,即使在关闭控制台或重新启动计算机后也是如此。 PowerShell 当前使用两个命令历史记录提供程序:当前会话中的命令历史记录(由 Get-History cmdlet 显示)和 PSReadLine 模块保存的包含先前命令的文本日志。

在 Windows 上查看 PowerShell 命令历史记录

在 PowerShell 控制台中,按向上键时会显示您输入的最后一个命令。如果继续按“向上”键,您将看到之前执行的所有命令。因此,使用“

Up arrow

“ 和 ”

Down arrow

” 键,您可以滚动浏览 PowerShell 命令的历史记录并重新运行以前键入的命令。如果您需要快速执行前面的命令之一而无需再次键入,这非常有用。

PowerShell 控制台保留自 Windows PowerShell 5.1(Windows 10 中默认安装)以来的完整命令历史记录。在以前版本的 Windows PowerShell(和 cmd 命令提示符)中,执行命令的历史记录仅在当前 PowerShell 会话中可用。使用Get-History cmdlet 查看当前会话中先前命令的历史记录。

您可以显示有关当前 PowerShell 会话中先前执行的命令的更多详细信息,包括命令状态和开始/结束/持续时间:

Get-History | Format-List -Property *

[玩转系统] 在 PowerShell 控制台中使用以前的命令历史记录

您可以通过其 ID 运行上一个命令:

Invoke-History 6

当您关闭 PowerShell 控制台时,命令历史记录将被重置,并且 Get-History 中的列表将被清除。

但是,Windows PowerShell 5.1 和 PowerShell Core 还将最后 4096 个命令保存在每个用户配置文件中的纯文本文件中

%userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt

您可以使用任何文本编辑器打开此文件并查看命令历史记录。例如,要使用记事本打开命令日志文件:

notepad (Get-PSReadLineOption | select -ExpandProperty HistorySavePath)

[玩转系统] 在 PowerShell 控制台中使用以前的命令历史记录

PowerShell 控制台和 PowerShell ISE 的历史日志分别保存。

在 cmd.exe 中,您可以使用以下命令显示当前会话中的命令历史记录:

doskey /history

F7

key 用于搜索 cmd 历史记录。

[玩转系统] 在 PowerShell 控制台中使用以前的命令历史记录

如何在PowerShell命令历史记录中搜索?

如果您不想使用向上/向下箭头滚动浏览整个 PowerShell 命令历史记录,可以使用键盘快捷键 CTRL+R (反向搜索)和 CTR +S(正向搜索)搜索命令历史记录。按组合键并开始键入要在以前执行的命令中查找的部分命令。您输入的文本将在命令历史记录中的任何位置找到(与在 PowerShell 中使用搜索不同)

F8

或者

Shift+F8

,它允许仅从行的开头查找匹配项)。 PowerShell 控制台应显示与搜索字符串对应的上一个命令。行匹配在命令中突出显示。

CTRL+R

/

CTRL+S

如果找到的命令不是您想要的,请再次继续搜索历史记录。结果,屏幕上将出现与搜索模式相对应的以下命令。

[玩转系统] 在 PowerShell 控制台中使用以前的命令历史记录

使用

F8

键,您可以在历史记录中搜索与当前命令行上的文本匹配的命令。例如,输入

get-

并按

F8

。将找到命令历史记录中与此文本匹配的最后一个条目。要转到历史记录中的下一个命令,请按

F8

再次。

[玩转系统] 在 PowerShell 控制台中使用以前的命令历史记录

您还可以使用

#

用于搜索命令历史记录的字符。例如,要查找以 Get-WMI 开头的最后一个命令,请键入

#get-wmi

并按

Tab

钥匙。与该模式匹配的最后一个命令将出现在控制台中:

[玩转系统] 在 PowerShell 控制台中使用以前的命令历史记录

命令历史记录在经典 Windows PowerShell 和新 PowerShell Core 中的工作方式相同(如果您已经升级了 PoSh 版本)。您可以使用 Windows 11 和 Windows 10 中内置的 WinGet 包管理器来快速更新 PowerShell 版本:

winget install --id=Microsoft.PowerShell -e

要显示历史记录中与查询匹配的命令列表,您可以使用:

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

和 :

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

[玩转系统] 在 PowerShell 控制台中使用以前的命令历史记录

Select-String cmdlet 可以在 PowerShell 中使用,就像 Linux 中的 grep 命令一样。

使用 PSReadLine 模块配置 PowerShell 命令历史记录

PowerShell 中的命令历史记录功能并未内置于 Windows Management Framework 本身中,而是基于 PSReadLine 模块,这大大增强了 PowerShell 控制台的功能。 Windows 上的 PSReadLine 模块位于 C:\Program Files\WindowsPowerShell\Modules\PSReadline 文件夹中,启动 PowerShell 控制台时会自动导入。

PSReadLine 在控制台中提供语法突出显示,负责使用鼠标选择文本及其复制/粘贴的能力

CTRL+C

CTRL+V

检查该模块是否已加载到当前的 PowerShell 会话中:

Get-Module

[玩转系统] 在 PowerShell 控制台中使用以前的命令历史记录

如果未加载 PSReadline 模块,请验证是否已安装。如有必要,请从 PowerShell Gallery 在线存储库安装它:

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

您还可以离线手动安装 PowerShell 模块。

用于管理 PowerShell 中的命令历史记录的 PSReadLine 模块的功能的完整列表以及分配给它们的键可以使用以下命令显示:

Get-PSReadlineKeyHandler | ? {$_.function -like '*hist*'}
Key       Function                Description
---       --------                -----------
UpArrow   PreviousHistory         Replace the input with the previous item in the history
DownArrow NextHistory             Replace the input with the next item in the history
Ctrl+r    ReverseSearchHistory    Search history backwards interactively
Ctrl+s    ForwardSearchHistory    Search history forward interactively
Alt+F7    ClearHistory            Remove all items from the command line history (not PowerShell history)
F8        HistorySearchBackward   Search for the previous item in the history that starts with the current input - like NextHistory if the input is empty
Shift+F8  HistorySearchForward    Search for the next item in the history that starts with the current input - like NextHistory if the input is empty
Unbound   ViSearchHistoryBackward Starts a new seach backward in the history.
Unbound   BeginningOfHistory      Move to the first item in the history
Unbound   EndOfHistory            Move to the last item (the current input) in the history

[玩转系统] 在 PowerShell 控制台中使用以前的命令历史记录

列出 PSReadLine 模块中当前的 PowerShell 命令历史记录设置:

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

[玩转系统] 在 PowerShell 控制台中使用以前的命令历史记录

您可能需要考虑以下 PSReadline 参数:

  • HistoryNoDuplicates - 是否必须保存相同的命令;

  • MaximumHistoryCount - 存储命令的最大数量(默认保存最后4096条命令);

  • HistorySearchCursorMovesToEnd — 搜索时是否需要跳转到命令末尾;

  • istorySearchCaseSensitive - 搜索是否区分大小写(PowerShell 命令历史记录默认情况下不区分大小写);

  • HistorySavePath - 存储 PowerShell 命令历史记录的文本文件的路径;;

  • HistorySaveStyle - 命令历史记录保存选项:

    • 增量保存 - 命令在执行时保存(默认情况下);

  • SaveAtExit - 关闭 PowerShell 控制台时会保存历史记录;

  • SaveNothing — 禁用保存命令历史记录。

您可以使用 Set-PSReadlineOption 命令更改 PSReadLine 模块设置。例如,要增加日志中存储的 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 控制台中使用以前的命令历史记录

用户配置文件现在包含每个 PowerShell 会话的详细日志文件

%USERPROFILE%\Documents\WindowsPowerShell\TranscriptLog

目录。

如何运行 PowerShell 命令而不将其保存到历史记录?

在 Linux bash shell 中,您可以禁用以空格开头的命令的历史记录(使用

HISTCONTROL= ignorespace

)。您可以为 PowerShell 配置类似的行为。

为此,请将以下代码添加到当前用户的 PowerShell 配置文件中(

$profile.CurrentUserAllHosts

):

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

[玩转系统] 在 PowerShell 控制台中使用以前的命令历史记录

此功能要求您将计算机上的 PowerShell 执行策略设置为 Remotesigned:

Set-ExecutionPolicy Remotesigned

现在,如果您不希望将命令保存在 PowerShell 命令历史记录中,只需以空格开始命令即可。

另外,从 Readline v2.0.4 模块版本开始,包含以下关键字的命令将被自动忽略并且不会保存到历史记录中:

Password

,

Asplaintext

,

Token

,

Apikey

,

Secret

。同时,SecretManagement 密码管理模块中的 cmdlet 被认为是安全的,并允许保存到历史文件中。

将预测性 IntelliSense 与 PowerShell 命令历史记录结合使用

PSReadLine 2.2.2+ 中提供了新的 PowerShell 预测 IntelliSense 功能。当您在 PowerShell 控制台中键入命令时,此功能会显示本地命令历史记录中最合适的命令。

在这个例子中,我输入了

get-wm

在控制台中,预测智能感知建议了我之前输入的与我的输入相匹配的命令之一。如果这个命令适合我,我需要按

right arrow key

接受此命令而不手动键入其余字符。

[玩转系统] 在 PowerShell 控制台中使用以前的命令历史记录

默认情况下,预测 IntelliSense 提示以灰色文本显示,并且在 PowerShell 控制台的黑色背景下难以阅读。此命令使建议的文本更具对比性:

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

从 PSReadLine 2.2.6 开始,默认情况下启用预测智能感知。您可以手动启用它:

Set-PSReadLineOption -PredictionSource History

要重置 IntelliSense 预测建议,请按 Esc 键。

您可以按F2键切换到另一个视图。现在,不再显示一个最合适的命令(

InlineView 

),将显示包含所有类似命令的下拉列表(

ListView

)。

[玩转系统] 在 PowerShell 控制台中使用以前的命令历史记录

使用向上/向下键从命令历史记录中快速选择所需的命令。

预测 IntelliSense 可在标准 pwsh.exe/powershell.exe 命令行以及 Windows 终端和 Visual Studio 代码中工作。

如何清除PowerShell中的命令历史记录?

正如我们上面所解释的,PSReadline 模块将所有 PowerShell 控制台命令保存到文本文件中。然而,在某些情况下,管理员必须在 PowerShell 控制台中输入各种敏感信息(凭据、密码、令牌、地址、个人数据等)。纯文本文件中的历史数据可以被其他服务器管理员或攻击者访问。出于安全原因,您可能必须清除已运行的 PowerShell 命令的历史记录或完全关闭命令历史记录。

Clear-History cmdlet 允许您仅清除当前 PowerShell 会话中的命令历史记录。它仅删除 Get-History 返回的上一个命令列表。

您只能从历史记录中删除一条先前的命令:

Clear-History -count 1 -newest

或者清除具有特定模式的所有命令:

Clear-History -CommandLine *set-ad*

要完全清除以前的 PowerShell 命令的历史记录,您需要删除 PSReadline 模块写入的 ConsoleHost_history.txt 文件。您可以获取当前的 PowerShell 历史文件位置并使用以下命令将其删除:

Remove-Item (Get-PSReadlineOption).HistorySavePath

之后,关闭 PowerShell 控制台窗口。

如果要完全禁止将 PowerShell 命令历史记录保存到文本文件,请运行以下命令:

Set-PSReadlineOption -HistorySaveStyle SaveNothing

[玩转系统] 在 PowerShell 控制台中使用以前的命令历史记录

如何将 PowerShell 命令历史记录导出/导入到另一个会话?

有时,在不同的计算机上使用同一组常用的 PowerShell 命令会很方便。您可以将计算机上的当前命令历史记录导出到 XML 文件并将其导入到其他计算机。您可以通过将用户配置文件中的 ConsoleHost_history.txt 文件复制到目标计算机来执行此操作。

您还可以使用

Export-Clixml

小命令

将命令历史记录从当前会话导出到文本文件:

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

要将命令历史记录从文件导入到另一个 PowerShell 会话(在本地计算机或另一台计算机上):

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

[玩转系统] 在 PowerShell 控制台中使用以前的命令历史记录

要在 PowerShell 会话结束时自动将先前的命令导出到文件,您可以将脚本绑定到 PoSh 会话结束事件(!!会话必须使用以下命令终止)

exit

命令,r,而不是简单地关闭 PowerShell 控制台):

$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 }

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯