common/Write-Log.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#region Log File Management
$logLocalAppDir = Join-Path $Script:mInfo.ModuleBase logs
$logName = "$($Script:mInfo.Name).log" 
$logFullName = Join-Path $logLocalAppDir $logName
$MaxLogFileSizeMB = 5 # After a log file reaches this size it will archive the existing and create a new one

trap
[Exception] 
{ 
    Write-Log
    "error: $($_.Exception.GetType().Name) - $($_.Exception.Message)" 
} 

function LogFileCheck 
{
    if (Test-Path $logFullName) #
    {
        if (((gci $logFullName).length/1MB) -gt $MaxLogFileSizeMB) # Check size of log file - to stop unweildy size, archive existing file if over limit and create fresh.
        {
            $NewLogFile = $LogName.replace(".log", " ARCHIVED $(Get-Date -Format dd-MM-yyy-hh-mm-ss).log") 
            $log = Rename-Item $logFullName (Join-Path $LogLocalAppDir $NewLogFile) -PassThru
            Write-Host "Log $($log.fullname)" -ForegroundColor Cyan
        }
    }
    else
    {
        if (!(Test-Path $LogLocalAppDir))
        {
            mkdir $LogLocalAppDir | Out-Null
        }
        New-Item $logFullName -type file 
    }
}



function Write-Log # Send to log file
{
    param(
            [Parameter(Mandatory=$false,ValueFromPipeline=$true)]
                [System.String]$message,
            [ValidateSet('INFO','WARNING','ERROR','EXCEPTION','SECURITY')]            
                [System.String]$Level="INFO"
        )
    if (-not $WhatIfPreference.IsPresent -and $message)
    {
        foreach($obj in $input)
        {
            $pipeline += $obj
        }

        if (![String]::IsNullOrEmpty($pipeline))
        {
            $message = $pipeline
        }
        try
        {
            $toOutput = "$(get-date) $($env:USERDOMAIN)\$($env:USERNAME) $($Level):$($message)" | Out-File $logFullName -append -NoClobber -ErrorAction SilentlyContinue -Encoding default
        }
        catch{}
    }
}



LogFileCheck
#endregion Log File Management