PowerShell : Function for logging events.
I have found that when writing scripts I don't do enough event logging, and when I do decide to log something its not usually enough.
Hence I have written this nice little block of code that creates functions specifically for creating and maintain a log for your amusement.
Just copy thing code into your script, set the constants like log location, then use:
Add-LogEvent -content "Add event text"
to log anything you like, remembering to run
Check-LogLength -EventsToSave $EventsToSave
at some point.
Your log will look like this:
$LogLocation ="c:\temp\"
$LogName = "testlog.txt"
$global:FullPath = $LogLocation + $LogName
$EventsToSave = 10
if (Test-Path -Path $FullPath) {}
Else{
mkdir $logLocation
New-Item $FullPath
Add-LogEvent "Log Created" $FullPath
}
Check-LogLength -EventsToSave $EventsToSave
Function Add-LogEvent {
Param ($content)
$time = Get-Date
$LogEvent = "Event : " + $time + " : " + $content
add-Content $FullPath $LogEvent
}
Function Check-LogLength {
Param ([Parameter(Mandatory=$true)]$EventsToSave)
$LogContent = Get-Content $FullPath
$EventsToPurge = $LogContent.Count - $EventsToSave
if ($EventsToPurge -gt 0)
{
For ($i=1; $i -le $EventsTopurge; $i++)
{
echo $i
$LogContent[$i] = $null
}
del $FullPath
New-Item $FullPath
Set-Content $FullPath $LogContent
}
}