查找并调用PowerShell历史记录中的命令行

我们通常会在Console界面中运行多次命令或者命令行,很多人会使用键盘的上下键来翻动之前使用的命令,但是当我们敲过运行的命令次数越多那么即便你去使用上下键去翻页查找之前使用的命令也依然会显得不是那么方便。

其实,在PowerShell中我们可以使用管理历史记录的命令来管理那些之前使用过的命令行,目前在PowerShell中有如下四个管理历史相关的命令。

          Cmdlet (Alias)       Description
          -------------------  ------------------------------------------
          Get-History (h)      Gets the command history.

          Invoke-History (r)   Runs a command in the command history.

          Add-History          Adds a command to the command history.

          Clear-History (clh)  Deletes commands from the command history.


如上面的Description介绍所描述的那样, 我们如下使用了Get-History命令得到如下从我们打开PowerShell Console界面开始记录的第一条命令。
 C:\Users\Administrator> Get-History

 Id CommandLine
 -- -----------
  1 registry
  2 cls
  3 $PSDefaultParameterValues = @{"Get-Process:Name" = "notepad"}
  4 gps
  5 gps -Verbose
  6 $PSDefaultParameterValues = @{"Get-Process:Name" = "notepad"}
  7 Get-Process
  8 $PSDefaultParameterValues = @{"Get-Process:Name" = {(Get-Process -Id 1204)|select processname}}

当然,PowerShell并不会无止境的记录历史命令,你可以通过使用如下保留自变量来查看系统默认可以记录多少历史命令:

PS C:\Users\Administrator> $MaximumHistoryCount
4096
你也可以直接给这个变量赋一个阿拉伯数字设置你想设置的上限值,比如我设置为5:

PS C:\Users\Administrator> $MaximumHistoryCount = 5
PS C:\Users\Administrator> $MaximumHistoryCount
5


当你在用Get-History命令查看记录了多少命令的时候你会发现,它只自动截取了最近的5行命令,而自动解掉了之前的命令。
PS C:\Users\Administrator> Get-History

  Id CommandLine
  -- -----------
  46 $MaximumAliasCount
  47 $MaximumHistoryCount = 200
  48 $MaximumHistoryCount
  49 $MaximumHistoryCount = 5
  50 $MaximumHistoryCount

我们可以使用Invoke-History或者别名r 来调用历史命令:

PS C:\Users\Administrator> Invoke-History -id 51
Get-History

  Id CommandLine
  -- -----------
  51 Get-History
  52 Invoke-History -id 46
  53 Invoke-History -Id 46
  54 Invoke-History -Id 46
  55 Get-History

好了,大致是这样,非常简单的几个命令,对了你还可以用Add-History添加命令或用Clear-History来清除之前的命令行。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值