1
2

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で一定期間経過したフォルダを削除する

Posted at

趣旨

あるフォルダ内で一定期間経過したフォルダを削除する必要があったので、備忘録的な自分用メモです。

実行コマンド

当月から2ヶ月前の「YYYYMM」名のフォルダを削除する場合

$now = (Get-Date).AddMonths(-2)
$delMonth = $now.ToString("yyyyMM");

Get-ChildItem D:\test\pdf | Where-Object {$_.Attributes -eq "Directory" -and $_.Name -eq $delMonth} | Remove-Item -recurse -force

当月から2ヶ月前の「YYYYMMDD」名のフォルダを全て削除する場合

$now = (Get-Date).AddMonths(-2)
$delMonth = $now.ToString("yyyyMM");

Get-ChildItem D:\test\pdf | Where-Object {$_.Attributes -eq "Directory" -and $_.Name -match "$delMonth(0[1-9]|[12][0-9]|3[01])"} | Remove-Item -recurse -force

念のため削除前に確認をしておく

Remove-Item -recurse -force
を
Sort-Object Name
に変更して、意図したフォルダ名が表示されていることを確認する

定期的な削除の実行

上記のスクリプトをバッチファイルから呼出し実行するバッチファイルを作成して
タスクスケジューラに、任意のトリガー(月一)でタスク実行されるように登録する

1
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?