PowerShell Tips

はじめに

時々必要になるが、その時には多分忘れているであろう知識を書き残しておく。自分が見て方針を思い出すためのメモなので基本的に解説はしないし、ここに書いてあるコードは厳密であるとは限らない。

特定のフォルダ以下の全てのファイルのタイム・スタンプを変更

$target_dir = $PSScriptRoot
$desired_CreationTime = '2001-01-01 01:02:03'
$desired_LastWriteTime = '2001-01-02 01:02:03'

Get-ChildItem -Path $target_dir -Recurse -Attributes !Directory | ForEach-Object -Process {
    $target_file = $_.FullName
    Set-ItemProperty -Path $target_file -Name CreationTime -Value $desired_CreationTime
    Set-ItemProperty -Path $target_file -Name LastWriteTime -Value $desired_LastWriteTime
}

コマンド履歴のエクスポートとインポート

エクスポート

# 保存先パスの確認
(Get-PSReadLineOption).HistorySavePath
# 任意の場所へコピー
Copy-Item (Get-PSReadLineOption).HistorySavePath -Destination "path\to\all_history.txt"

インポート。バックアップしたテキストファイルを現在の環境に反映させる。環境に合わせて「上書き」か「追記」を選択する。

  • 丸ごと上書き(別PCへの移行など):Copy-Item -Path "C:\path\to\all_history.txt" -Destination (Get-PSReadLineOption).HistorySavePath -Force
  • 末尾に追記(現在の履歴を残して統合):Get-Content -Path "C:\path\to\all_history.txt" | Add-Content -Path (Get-PSReadLineOption).HistorySavePath

自分のお気に入り設定

# Related: https://github.com/PowerShell/PSReadLine/issues/1778
Set-PSReadLineKeyHandler -Key Shift+Delete `
    -BriefDescription RemoveFromHistory `
    -LongDescription "Removes the content of the current line from history" `
    -ScriptBlock {
    param($key, $arg)

    $line = $null
    $cursor = $null
    [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)

    $toRemove = [Regex]::Escape(($line -replace "\n", "```n"))
    $history = Get-Content (Get-PSReadLineOption).HistorySavePath -Raw
    $history = $history -replace "(?m)^$toRemove\r\n", ""
    Set-Content (Get-PSReadLineOption).HistorySavePath $history
}

# Does not save duplicate commands (equivalent to ignoredups in bash).
Set-PSReadLineOption -HistoryNoDuplicates

# Does not save commands that start with a space (equivalent to ignorespace in bash).
Set-PSReadLineOption -AddToHistoryHandler {
    param([string]$line)
    return -not $line.StartsWith(" ")
}

コメントを残す