LoginSignup
0
3

More than 3 years have passed since last update.

PowerShellを使ってIISログを定期的に圧縮・削除する

Last updated at Posted at 2021-04-04

趣旨

オンプレのSharePoint Server構築案件で必要になったので作成した。

要件:
・過去180日より古いIISログをzipに圧縮する
・圧縮したファイルは365日間保存する。それを超えたら削除する

Powershell ソースコード

#-------------------------------------------------
#変数の設定
#-------------------------------------------------
#region
#IISログフォルダのパス
$IISLogFolderPath = "C:\inetpub\logs\LogFiles\W3SVCXXXXXX\"

#IISログの保持期限(単位:日)
#補足:この期限を超えたら圧縮する。圧縮元のIISログは削除する。
$IISLogRetentionPeriod = 180

#圧縮したIISログを保存するフォルダのパス
$folderPathToSaveCompressedIISLog = "C:\inetpub\logs\LogFiles\W3SVCXXXXXX\\アーカイブ保存\"

#圧縮したIISログの保持期限(単位:日)
#補足:この期限を超えたら削除する。
$compressedIISLogRetentionPeriod = 365

#endregion
#-------------------------------------------------
#古いIISログを圧縮する
#-------------------------------------------------
#圧縮したIISログを保存するためのフォルダがなければ作成する
if((Test-Path -Path $folderPathToSaveCompressedIISLog) -eq $false)
{
    New-Item $folderPathToSaveCompressedIISLog -ItemType Directory
}

#IISログをすべて取得
$IISLogs = Get-ChildItem -Path $IISLogFolderPath -File 

#古いIISログを圧縮
foreach($IISLog in $IISLogs)
{
    #ファイル名をもとに作成日を取得する
    $matchedIISLogCreatedDateString = [RegEx]::Matches($IISLog.BaseName,"\d{6}$")
    $IISLogCreatedDate              = [DateTime]::ParseExact($matchedIISLogCreatedDateString.value,"yyMMdd", $null)

    #作成日から経過した日数を取得
    $timeSpanFromIISLogCreated = (Get-Date) - $IISLogCreatedDate

    #作成日から保持期限が経過していなければ処理をスキップする
    if($timeSpanFromIISLogCreated.Days -lt $IISLogRetentionPeriod)
    {
        continue
    }

    #圧縮ファイルのフルパスを定義
    $destinationPath = $folderPathToSaveCompressedIISLog + $IISLogCreatedDate.Date.ToString("yyyyMMdd") + ".zip"

    Compress-Archive `
    -Path            $IISLog.FullName `
    -DestinationPath $destinationPath `
    -Update

    #圧縮前のファイルを削除
    Remove-Item -Path $IISLog.FullName
}

#-------------------------------------------------
#古い圧縮ファイルを削除する
#-------------------------------------------------
#圧縮したIISログファイルをすべて取得する
$compressedIISLogs = Get-ChildItem -Path $folderPathToSaveCompressedIISLog -File 

#古い圧縮ファイルを削除
foreach($compressedIISLog in $compressedIISLogs)
{
    #ファイル名をもとに作成日を取得する
    $compressedIISLogCreatedDate = [DateTime]::ParseExact($compressedIISLog.BaseName,"yyyyMMdd", $null)

    #作成日から経過した日数を取得
    $timeSpanFromCompressedIISLogCreated = (Get-Date) - $compressedIISLogCreatedDate

    #作成日から保持期限が経過していなければ処理をスキップする
    if($timeSpanFromCompressedIISLogCreated.Days -lt $IISLogRetentionPeriod + $compressedIISLogRetentionPeriod)
    {
        continue
    }

    #ファイルを削除
    Remove-Item -Path $compressedIISLog.FullName
}


実行結果のイメージ

image.png

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