見出し画像

【PowerShell】ファイル名にミリ秒までのタイムスタンプを付けるスクリプト

はじめに

 ファイルの並べ替えのときに、名前順や更新日時順にすることがありますが、名前と更新日時の複数条件で並び替えたいときがあります。

例)ホスト名毎に時刻順に並べたい場合、下記のようなファイル名にし、名前順にすればよい(日付 -時分秒- ミリ秒)
    hostname1_20240914-1501-111111.log
    hostname1_20240915-1600-222222.log
    hostname2_20240914-1500-101010.log
    hostname2_20240915-1601-111111.log

動作イメージ

下記のようなフォルダ構成で
beforeフォルダにタイムスタンプなしのファイルを入れる。(hostname1.log、hostname2.logなど)
batをダブルクリックで実行する
afterフォルダにタイムスタンプ付きのファイルが入る。
(hostname1_20240914-1501-111111.logなど)

コード

renameFilesWithMillisecTimestamp.bat

出力先フォルダ(after)を中身ごと削除後に生成。
その後、ps1ファイルのブロックを解除した後、ps1ファイルを実施する。

@echo off

rmdir /s /q after
mkdir after
powershell.exe -ExecutionPolicy RemoteSigned -Command Unblock-File .\renameFilesWithMillisecTimestamp.ps1


cd before
powershell.exe -ExecutionPolicy RemoteSigned ..\renameFilesWithMillisecTimestamp.ps1

pause

renameFilesWithMillisecTimestamp.ps1

extentionは拡張子のこと


# カレントディレクトリのファイルリストを作成
$fileList = Get-ChildItem -Recurse -Name

# ファイルごとにリネーム処理
$currentDir = Convert-Path .
foreach($filename in $fileList){

  $extention = [System.IO.Path]::GetExtension($filename);
  $filenameWithoutExtention = [System.IO.Path]::GetFileNameWithoutExtension($filename);
  $timestamp = $(Get-Item $filename).LastWriteTime.ToString("yyyyMMdd-HHmmss-ffffff")

  $fnAfter  = "..\after\" + $filenameWithoutExtention + "_" + $timestamp + $extention
  $fpBefore = $currentDir + "\" + $filename

  if(Test-Path $fpBefore){
    Copy-Item -Path $fpBefore $fnAfter
  }
}


参考 ファイルシステムと時間分解能

Cドライブのプロパティで、ファイルシステムがNTFSと確認できる。

また、時間の解像度については、公式ドキュメントはないもののwikipediaに日付分解能 100ナノ秒と記載があり、各ブログでも100ナノ秒と記載されている。


この記事が気に入ったらサポートをしてみませんか?