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 (
        [Parameter(Mandatory=$True)]
        [array]$LogOutput,
        [Parameter(Mandatory=$True)]
        [string]$Path
	)
	$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:

try{
something right!
}
Catch{
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:
      try{
      Copy-Item -Path “C:\Users\Morten\desktop\teststuff” -Destination “\\Publicshare\ForAll$”
      }
      Catch{
      write-log -LogOutput (“Failed to do something right: {0}” -f $_) -Path $LogFile
      }

      Reply

Leave a comment