LoginSignup
23

More than 5 years have passed since last update.

このコマンドレット、この前 PowerShell で実行した、ような・・・・・・

Last updated at Posted at 2013-09-21

こんなの絶対おかしいよ!

Powershell で、いろいろ操作して、昨日打ったコマンドを、また実行できると、それはとっても嬉しいなって思うのですが、Powershell を一旦終了してしまうと履歴が保存されずに消えてしまっています。。。

それでもいいの?
さっき打ったコマンドレットを忘れちゃうのに?
さっき打ったコマンドレットのこと、もう二度と感じ取ることさえ出来なくなっちゃうのに??

履歴保存も、履歴補完も、あるんだよ

がんばれば、きちんとした履歴保存機能を作ることができるでしょうが、
できるだけがんばらずに、履歴保存する方向で。

履歴保存も、あるんだよ

  • $Profile の中の function PromptExport-Csv -Path ~\.posh_history.csv -InputObject (Get-History)[-1] -Append を追記
  • ただし、 exit 以外の方法で終了してしまうと、最後に実行した履歴が残らない(終了イベントとかで保存すればいいけど面倒。そこまでするなら、プラグイン化するか、既存のものを使いたい
  • あと、コマンドなしで Enter を連打してしまうと同じ履歴が、いっぱい残ってしまう(面倒。そこまでするなら(以下略
  • PowerShell 3.0 以上じゃないと、 Export-Csv に -Append オプションがないので、Out-File コマンドで、csv に追記する(初回にヘッダありのファイルを作成しなければならない。。。3.0に比べて、かなり面倒。。。) PowerShell 2.0 のことは忘れましょう
# 2.0 向け(PowerShell 2.0 のことは忘れましょう
if (-not (Test-Path ~\.posh_history.csv)) {
    "#TYPE Microsoft.PowerShell.Commands.HistoryInfo" | Out-File ~\.posh_history.csv -encoding UTF8
    '"Id","CommandLine","ExecutionStatus","StartExecutionTime","EndExecutionTime"' | Out-File ~\.posh_history.csv -encoding UTF8 -append
}
$h = (Get-History)[-1]
$csv = "`"$($h.Id)`",`"$($h.CommandLine)`",`"$($h.ExecutionStatus)`",`"$($h.StartExecutionTime)`",`"$($h.EndExecutionTime)`""
$csv | Out-File ~\.posh_history.csv -encoding UTF8 -append

履歴読込も、するんだよ

  • $Profile に Import-Csv ~\.posh_history.csv | Add-History を追記

履歴補完も、あるんだよ

  • #検索したい文字列<Tab>

$Env
function Prompt {
    # PowerShell 3.0+
    Export-Csv -Path ~\.posh_history.csv -InputObject (Get-History)[-1] -Append
    return "$pwd > "
}

Import-Csv ~\.posh_history.csv | Add-History

参考

追記

はやく Windows 10 に移行しましょう。

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
23