0
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?

日付別ファイル圧縮.ps1

Posted at

1. スクリプト概要

スクリプト名: 日付別ファイル圧縮.ps1
指定されたフォルダ内のファイルを更新日ごとにZIP圧縮し、元のファイルを削除します

2. 処理と目的

処理の流れ
 1. 対象フォルダのフルパスで入力します
 2. 対象フォルダ内のZIPファイル以外のファイルを検索します
 3. 圧縮対象とするファイルの基準日を入力します
 4. 対象ファイルを更新日ごとにarchive_YYYY-MM-DD.zipというファイル名で圧縮し、保存します
 5. 手順4で圧縮されたファイルを削除します

目的
 大量のログファイルが保存されているフォルダを整理する際に、ファイルを日付ごとに分類しつつ、ファイル数を削減することを目的としています

3. 動作環境と要件

PowerShellのバージョン
7.0以上

OS
Windows10

必要なモジュール
特になし

必要な権限
特になし

その他の設定
特になし

4. 使用方法

基本的な実行方法
スクリプトコードを拡張子ps1で保存してPowershellで実行してください。
ファイルを保存する際は、文字コードをUTF8 BOM付にしてください。

パラメータ
なし

使用例

  1. コマンドラインでpwsh 日付別ファイル圧縮.ps1を実行
  2. 検索対象フォルダの入力を促すので、フォルダのフルパスを入力します
  3. 対象とするファイルの基準日の入力を促すので、基準日をYYYY/MM/DD形式で入力します

5. スクリプトコード

if( $PSVersionTable.PSVersion.Major -ge 7 -and ((ps -Id $PID | ?{$_.Parent.ProcessName -notin @('pwsh','powershell')}) -ne $null)){
    cls
}

# ウィンドウタイトルをスクリプト名に設定します。
$host.UI.RawUI.WindowTitle = ([IO.Path]::GetFilenameWithoutExtension($PSCommandPath))

# エラー発生時にスクリプトの実行を停止するように設定します。
$ErrorActionPreference = 'Stop'

Write-Host "--------------------------------------------------------------------------" 
Write-Host "対象フォルダ内のファイルを更新日時別でzip圧縮します" -ForegroundColor White -BackGroundColor Black
Write-Host "圧縮後に元ファイルは削除します" -ForegroundColor White -BackGroundColor Black
Write-Host "圧縮対象のファイルは指定日付以前のものだけです" -ForegroundColor White -BackGroundColor Black
Write-Host "--------------------------------------------------------------------------"

# ユーザーから有効な対象フォルダが入力されるまで繰り返し入力を促します。
do {
    $taishoDir = Read-Host "対象フォルダ"
} while(-not [IO.Directory]::exists($taishoDir))

# ファイルフィルターを全てに設定します(ただし、後で.zipファイルは除外されます)。
$fileFilter = '*.*'

# 対象フォルダ内の全てのファイルを取得し、.zipファイルを除外します。
$allFiles = ls -LiteralPath $taishoDir -Filter $fileFilter | ?{$_.Extension -notin @('.zip')}

# ユーザーから有効な対象日付が入力されるまで繰り返し入力を促します。(入力された日付は現在の日付よりも過去である必要があります。)
do {
    $inputText = Read-Host "対象日付(YYYY/MM/DD)"
    try {$taishoDate = Get-Date $inputText} catch {continue}
} while( (-not $taishoDate) -or $taishoDate -gt (Get-Date))

# 対象ファイルの中から、更新日時が対象日付以前のファイルの日付を抽出し、重複を排除してソートします。
$datelist = $allFiles | %{ Get-Date -Year $_.LastWritetime.Year -Month $_.LastWritetime.Month -Day $_.LastWritetime.Day -Hour 0 -Minute 0 -Second 0 -Millisecond 0} | sort -Unique | ?{$_ -le $taishoDate}

if(($datelist|Measure).Count -le 0){
    echo "「${taishoDate}」以前のファイルなし"
    pause
    return
}
echo $datelist
pause

# 日付リストの各日付に対して以下の処理を実行します。
foreach($taishoDate in $datelist){
    echo $taishoDate
    
    # 現在の対象日付に更新されたファイルを抽出します。
    $taishoFiles = $allFiles | ?{$_.LastWritetime -ge $taishoDate -and $_.LastWritetime -lt ($taishoDate.AddDays(1))}

    $taishoCount = ($taishoFiles | measure).Count
    echo "[${taishoDate}] ${taishoCount} 個のファイルが対象です"

    # 対象ファイルが0個の場合、次の日付の処理に移ります。
    if($taishoCount -eq 0){
        continue
    }

    # 圧縮ファイルのパスを生成します。ファイル名が重複する場合は連番を付加します。
    $counter = 0
    do {
        if($counter -eq 0){
            $dstPath = Join-Path $taishoDir ('archive_' + $taishoDate.ToString("yyyy-MM-dd") + ".zip")
        } else {
            $dstPath = Join-Path $taishoDir ('archive_' + $taishoDate.ToString("yyyy-MM-dd") + "_${counter}.zip")
        }
        $counter++
    } while(Test-Path -LiteralPath $dstPath)
    
    Write-Host "dstPath=${dstPath}"  -ForegroundColor Cyan

    # 圧縮先のファイルが存在しない場合のみ圧縮を実行します。
    if(-not(Test-Path -LiteralPath $dstPath)){
        Compress-Archive -LiteralPath ($taishoFiles|%{$_.FullName}) -DestinationPath $dstPath -ErrorAction Stop
        
        # 圧縮が成功した場合、元のファイルを削除します。
        if(Test-Path -LiteralPath $dstPath){
            $taishoFiles | %{Remove-Item -LiteralPath $_.FullName -Force}
        }
    } else {
        Write-Warning "圧縮先のファイルが既に存在します!"
    }
}

pause

6. 注意事項と既知の問題

制約事項
大量のファイルやサイズの大きいファイルを処理する場合、完了までに時間がかかる可能性があります。

既知のバグ
もしバグを発見された場合は、コメントでご報告ください。

トラブルシューティング
・ps1ファイルのエンコーディングには注意してください。

7. 免責事項

本スクリプトにはいかなる保証もありません。使用は自己責任で行ってください。

0
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
0
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?