Scripts/Log.ps1

#
# Log.ps1
#

Function Global:Start-Logging($Config){
    If ($Config.Log.IsLogging){
        $StartTime = (Get-Date –F s).Replace(':','')
        $Global:LogDirectory = Join-Path (Get-ProgramDataDirectory) "Logs\$StartTime"
        New-Item $LogDirectory -ItemType Directory -Force | Out-Null
        Start-Transcript (Join-Path $LogDirectory "Transcript.log")

        $Config | ConvertTo-Json -Depth 10 | Out-File -FilePath (Join-Path $LogDirectory "Config.json") -Encoding UTF8

        $LogsDirectoryChildItems = (Get-ChildItem (Join-Path (Get-ProgramDataDirectory) "Logs") -Directory -Filter "20*")
        If ($LogsDirectoryChildItems.Length -gt $Config.Log.MaximumCount){
            ForEach ($LogsDirectoryChildItem in $LogsDirectoryChildItems){
                #西暦上2桁"20"から始まるディレクトリを検索
                If ((Get-ChildItem (Join-Path (Get-ProgramDataDirectory) "Logs") -Directory -Filter "20*").Length -le $Config.Log.MaximumCount){
                    break
                }
                $LogsDirectoryChildItem | Remove-Item -Recurse -Force
            }
        }
    }
}

Function Global:Stop-Logging{
    Try{ Stop-Transcript }
    Catch{}
}