1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

過去の日付のテキストファイルを一括作成するPowerShellスクリプト

Last updated at Posted at 2021-03-26

#趣旨

ログファイルの定期削除ツールの開発をすることになって、作成日時や更新日時が過去のファイルが大量に必要になった。

なので、掲題のPowerShellスクリプトを作った。

Powershell ソースコード

#フォルダのパスを定義
$logFolderPath = "C:\work\Logs\"

#フォルダを作成
New-Item $logFolderPath -ItemType Directory

#何日分のファイルを作成するか
$days = 365

for($i=0;$i -lt $days;$i++)
{
    #ファイルパスを定義
    $today = Get-Date
    $targetDay = $today.AddDays(-$i)
    $logFile = $logFolderPath + "Log_hogehoge_" + $targetDay.ToString("yyyyMMdd") + ".txt"

    #本文
    $message = "dummy"

    #テキストファイルを出力
    Write-Host $targetDay.ToString("yyyy/MM/dd")
    $message | Out-File $logFile -Append -Encoding UTF8

    #作成日時、更新日時、アクセス日時を更新
    Set-ItemProperty -Path $logFile -Name CreationTime   -Value $targetDay.ToString("yyyy/MM/dd")
    Set-ItemProperty -Path $logFile -Name LastWriteTime  -Value $targetDay.ToString("yyyy/MM/dd")
    Set-ItemProperty -Path $logFile -Name LastAccessTime -Value $targetDay.ToString("yyyy/MM/dd")
}

#実行結果のイメージ
image.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?