Logging template for Powershell

This provides the code for a new project, to allow logging.

#[Powershell code]
# Purpose: Generic template for projects
# Author : Roger C  8-Mar-2018
# Purpose
$Version = "1.0.0.0"

$Main = {
    Init-LogFile
    Writeln-Log "Purpose: this is generic code"
    Writeln-Log "Process begins"
    Writeln-Log "Process ends"
}

#===[ Functions ]========================================================================
Function Writeln-Log($s)  {
    $s = (Get-Date -Format "hh:mm:ss.ff") + " $s"
    write-Host $s
    $s | Add-Content -Path ($LogFilename)
}

Function Init-LogFile { #-----------------------------------------------------------------
    # Define the log filename
    $MaxLogFileSize = 5000
    $global:LogPath = split-path $MyInvocation.ScriptName
    $global:LogFilename = (split-path $MyInvocation.ScriptName -leaf).replace(".ps1", ".log")
    $OldLogFilename = $LogFilename.replace(".log", ".old")
    $global:LogFilename = $LogPath + "\" + $LogFilename

    # If the log is larger than $MaxLogFileSize, cycle it to the .old log
    if (Test-Path $LogFilename) {
        if ((Get-Item $LogFilename).length -gt $MaxLogFileSize) {
            if (Test-Path ($LogPath + "\" + $OldLogFilename)) 
                { Remove-Item ($LogPath + "\" + $OldLogFilename) }
            Rename-Item -path $LogFilename -newname $OldLogFilename
        }
    }

    # write the header line
    $s = ("===[ "    + (get-date -uformat "%m/%d/%Y" ) `
    + " ]=========[ User: " + [System.Security.Principal.WindowsIdentity]::GetCurrent().Name `
    + " ]=======" )
    $s | Add-Content -Path ($LogFilename)
}

#---[ Call the main routine ]-------------------------------------------------------------
&$Main
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s