Simple log function with Powershell

When it comes to powershell logging in simple scripts i always use this. Each time you use the function it writes the time and append the text to a .log file.
The two variables $LogFolder and $LogFile can be changed as desired.

#Creating logoutput and filenames
$LogFolder = "C:\Users\Public\Documents"
$LogFile = $LogFolder + "\" + (Get-Date -UFormat "%d-%m-%Y") + ".log"

Function Write-Log
	param (
	$currentDate = (Get-Date -UFormat "%d-%m-%Y")
	$currentTime = (Get-Date -UFormat "%T")
	$logOutput = $logOutput -join (" ")
	"[$currentDate $currentTime] $logOutput" | Out-File $Path -Append

An example on how to use it:

something right!
write-log -LogOutput ("Failed to do something right:  {0}" -f $_) -Path $LogFile

Suggestions appreciated

2 thoughts on “Simple log function with Powershell”

    • hi,
      You would put your code in in the try/catch statement. Like so:
      Copy-Item -Path “C:\Users\Morten\desktop\teststuff” -Destination “\\Publicshare\ForAll$”
      write-log -LogOutput (“Failed to do something right: {0}” -f $_) -Path $LogFile


Leave a comment