Powershell logging function with date and time stamp
Logging Function
While I made this function a few times on demand with different purposes, I gathered a nice clean script somewhere (not sure where I found it) to start logging to a file.
I added the date/time stamp together with a write-host command to get the logging also on screen. This is a script I know always copy in my scripts to get a fast and simple logging function
#Variable to set the logfile location $Logfile = "D:\LogFile.txt" Function LogWrite{ <# .SYNOPSIS Simple function to write to a appending logfile with date and time stamp .PARAMETER $LogString Input parameter which holds the data which goes to the $logfile .PARAMETER $Logfile Parameter which contains the location of the logfile the information is written to .EXAMPLE LogWrite "Starting with $StrTitle files" LogWrite "Found $StrTitle files with an amount of $TotalSize MB." .NOTES Version: 1.0 Creation Date: 26-08-2014 Purpose/Change: PRD #> Param ([string]$logstring) Add-content $Logfile -value (((Get-Date).ToString()) + " " + $logstring) Write-Host (((Get-Date).ToString()) + " " + $logstring) }
Exection is as simple as :
logwrite "This line is being sent to screen and text file while a date & time stamp is added"
Powershell shows:
PowerCLI C:\> logwrite "This line is being sent to screen and text file while a date & time stamp is added" 30-8-2014 10:05:52 This line is being sent to screen and text file while a date & time stamp is added
And the text file:
30-8-2014 10:05:52 This line is being sent to screen and text file while a date & time stamp is added
Hopefully it can help someone just copy/paste and adjust where needed:)