PoshCode Archive  Artifact [1cb36fa63f]

Artifact 1cb36fa63f9c92629238792d85ad20faaed9b84373492df0e5c2932f000c3af0:

  • File Script-logging.ps1 — part of check-in [6267ec5f43] at 2018-06-10 13:19:08 on branch trunk — Add to top of your scripts and the script will automatically create a log file called <script name>.log to the AppData folder (user: shauncroucher size: 2211)

# encoding: ascii
# api: powershell
# title: Script logging
# description: Add to top of your scripts and the script will automatically create a log file called <script name>.log to the AppData folder 
# version: 0.1
# type: script
# author: shauncroucher
# license: CC0
# x-poshcode-id: 3032
# x-archived: 2014-10-21T20:00:10
# x-published: 2014-10-31T03:48:00
#
# The location is in a folder called PS_Data. 
# #
# If the location or file do not exist, this script will sort this out. If the script file grows large, it will archive by renaming the log file and create
# a new one.
# #
# Has been designed to run in conjunction with trace32.exe – Configmr tool for reading SMS log files. It will record exception errors in your script file and 
# log them with the keyword ‘error’ so they are highlighted in trace32.exe. 
# An additional function called sendl will allow you to easily write out to the log file – simply use sendl “message for log file”. 
# # #
#
#region Log File Management 
$ScriptName = $MyInvocation.mycommand.name 
$LocalAppDir = "$(gc env:LOCALAPPDATA)\PS_Data" 
$LogName = $ScriptName.replace(".ps1", ".log") 
$MaxLogFileSizeMB = 5 # After a log file reaches this size it will archive the existing and create a new one 

trap
[Exception] { 
sendl
"error: $($_.Exception.GetType().Name) - $($_.Exception.Message)" 
} 
function LogFileCheck 
{
if (!(Test-Path $LocalAppDir)) # Check if log file directory exists - if not, create and then create log file for this script. 
{
mkdir $LocalAppDir 
New-Item "$LocalAppDir\$LogName" -type file 
break 
}
if
(Test-Path "$LocalAppDir\$LogName") {
if (((gci "$LocalAppDir\$LogName").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") 
ren "$LocalAppDir\$LogName" "$LocalAppDir\$NewLogFile" 
}
}
}
function sendl ([string]$message) # Send to log file 
{
$toOutput
= "$(get-date) > $message " | Out-File "$LocalAppDir\$LogName" -append -NoClobber 
}
LogFileCheck
#endregion Log File Management