【ツールの概要】
・Powershellで、日別で作られるログフォルダ、データフォルダなどを週次で基準より古いものを圧縮するPowershellスクリプト。
【環境(使っている環境)】
・Windows Server2016
・Powershell ver5.1
【ソース(PS_LogArchiver.ps1)】
# ログfunction function logwrite($MSG, $INFO, $outputfile) { $NOW = Get-Date -Format G Write-Output "[ $NOW ][ $MSG ] $INFO" | Out-File -Append $outputfile -encoding Default } # ここではlogフォルダの中に、日次でフォルダが新規で作られている想定。それとこのスクリプトのログ(月別) $targetFolder = 'D:\log\'; $logfile = 'D:\PCompressLog\log\CompressLog_GetJson_' + (Get-Date -Format "yyyyMM") + '.log'; # 対象のlogフォルダの一覧を作成日でソート(降順) $List = Get-ChildItem $targetFolder | Sort-Object -Descending { $_.CreationTime } # ログに処理数書くため $i = 0; # logフォルダの中のアイテムについて、「フォルダかどうか」そして「21日前より前」かどうかで処理分岐 foreach ($item in $List) { if ($item.PSIsContainer -And ($item.CreationTime -lt (Get-Date).AddDays(-21))) { # セミコロン使うか使わないか統一しろっての(自戒) $zipfullpath = "$($item.FullName).zip"; # CompressArchiveこけるとエラるのでtrycatch。成功したらログ+オリジナル削除。失敗はログしてログの中身を書き出し。 try { compress-archive -Path $item.FullName -DestinationPath $zipfullpath logwrite "INF" "Files-compressed. itemname : $($item.FullName)" $logfile Remove-Item -Path $item.FullName -Recurse -Force $i++ } catch { logwrite "ERR" "Error. Files-compress Failed. itemname : $($item.FullName)" $logfile $errstring = $error[0] | Out-String logwrite "ERR" "$errstring" $logfile } } } logwrite "INF" "Compressed Files Count : $($i)" $logfile
【使用方法】
・対象フォルダの中の更にフォルダのみを対象としています。
・$targetFolder、$logfile をそれぞれ環境に沿って設定します。
・powershellで実行します。
【説明】
・非常に基本的な記述のみを使っていると思います。
・ログ出力やtrycatchにこだわらなければ、ソートの行のところで、一行でも終われるかもしれません。
【総評】
Windowsでは、powershellはbatに比べ非常に記述しやすいかと思います。
VBSと比べてナウい(?)感じがしますね!