LoginSignup
1
0

More than 5 years have passed since last update.

【PowerShell】Get-Historyを強化してコマンドの全履歴を取得するモジュールを作成した

Last updated at Posted at 2019-03-10

■今回つくったもの

PowerShellモジュールGet-All-History

■自分が試した環境

  • Windows10
  • PowerShell 5.1

■モジュール作成の経緯

Get-Historyが使いにくい

  • コマンドの全履歴をみたいのに、一回PowerShellを閉じちゃうとそこでの履歴は見れない。

Get-All-Historyができること

  1. 過去に実行したコマンドすべての履歴を取得できる
  2. 指定数だけ表示できる
  3. ID指定ができる(ID表示未対応のため使いづらさマックス)

過去に実行したコマンドすべての履歴をする

PS> Get-All-History

下記コマンドを実行すると、コマンドの全履歴が記録されたテキストファイルのパスが取得できる。
今回作成のモジュールは、これを参照して履歴を表示している。

PS> (Get-PSReadLineOption).HistorySavePath

指定数だけ表示する

PS> Get-All-History -Count 5

最新の5件分の履歴を取得

取得する履歴をIDで指定する

PS> Get-All-History -Id 5

コマンドは実行できるものの、Id表示に対応してないのでどの履歴がどのIdに紐付いてるかがわかりにくいと思うので、ほぼ使えないオプションです...
一応説明しておくと、一番古い履歴のIdが1です。

■コマンドレットを初めて作成してみた

これを見てつくりました。
▼PowerShell のモジュール詳解とモジュールへのコマンドレット配置手法を考える

今回モジュールのファイル名をgetAllHistory.psm1にしたので、
$env:USERPROFILE\Documents\WindowsPowerShell\Modulesディレクトリ内に、
ファイル名と同じ名前のディレクトリを作成しました。

■よくわからなかった点

PowerShell ISEで実行したコマンドの履歴ファイルが作成されない

このエントリーで言及している「コマンドの実行履歴」はPowerShellで実行したものを指します。
※ISEでの履歴は含まれません。

■改良したい点

Idと履歴が表示できるようにしたい

現状は履歴のみ

■コード

getAllHistory.psm1
function Get-All-History {
    Param(
        [Int]$Id,
        [Int]$Count = -1
    )

    # (Get-PSReadLineOption).HistorySavePath 実行で出てくるテキストファイルパスを指定します。
    $historyFile = "テキストファイルのパス"
    $hls = (Get-Content -Encoding utf8 $historyFile -Tail $Count) -as[string[]]

    # int型の初期値は0
    If($Id -ne 0) {
        Write-Host $hls[$Id]
    } Else {
        foreach($h in $hls) {
            Write-Host $h
        }
    }
}

Export-ModuleMember -Function Get-All-History

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0