Write-LogFile

Here is a function to allow a script to log its execution.
Output data into a log file. Options for path, extension and overwrite.

 

function Write-LogFile {
<#
.SYNOPSIS
Output data into a log file.
.DESCRIPTION
Output data into a log file. Options for path, extension and overwrite.
.PARAMETER  LogData
Data to be logged.
.PARAMETER  FolderPath
Path of the folder to store the log file in.
.PARAMETER  Extension
Use a different file extension other than .log .
.PARAMETER  Overwrite
Specify to overwrite existing log file.
.EXAMPLE
PS C:\> Write-LogFile -LogData $string -FolderPath 'C:\Logs' -Overwrite
.EXAMPLE
PS C:\> $string | Write-LogFile -FolderPath 'C:\Logs' -Extension 'txt'
#>
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, HelpMessage="Data to be logged")]
[ValidateNotNullOrEmpty()]
[String]
$LogData,
[Parameter(Position=1, Mandatory=$true, HelpMessage="Path of the folder to store the log file in")]
[ValidateNotNullOrEmpty()]
[String]
$FolderPath = 'D:\LOGS',
[Parameter(Position=2)]
[String]
$Extension = 'log',
[Parameter(Position=3)]
[Switch]
$Overwrite
)
process {
try
{
$Filename = [string](Get-Date -format yyyyMMdd) + '.' + $Extension

if ($Overwrite){
$LogData | Out-File $FolderPath\$Filename
}
else {
$LogData | Out-File $FolderPath\$Filename -Append
}
}
catch [System.IO.DirectoryNotFoundException]
{
Write-Host "The FolderPath $FolderPath does not exist. Please use a valid folder to store the log file in."  -ForegroundColor Red
}
}
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top