Public/Write-CustomLog.ps1
<#
.SYNOPSIS Writes custom log messages to a specified log file and outputs to the verbose stream. .DESCRIPTION The Write-CustomLog function is used to append custom log messages to a specified file. If no file is specified, it will only output to the verbose stream. The function supports logging multiple messages and will create the log file if it does not exist. .PARAMETER LogPath Specifies the path of the log file where the log messages will be written. If the file does not exist, it will be created. .PARAMETER Message Specifies the log messages to write. This parameter accepts input from the pipeline. .EXAMPLE Write-CustomLog -LogPath "C:\Logs\MyLog.log" -Message "This is a test log entry." Writes a single log entry to 'C:\Logs\MyLog.log'. .EXAMPLE "This is a test log entry." | Write-CustomLog -LogPath "C:\Logs\MyLog.log" Demonstrates pipeline input by writing a single log entry to 'C:\Logs\MyLog.log'. .EXAMPLE Write-CustomLog -Message "Processing started." -Verbose Writes a message to the verbose stream indicating that processing has started. .NOTES Author: Sundeep Eswarawaka Version: 1.0 This cmdlet supports the -Verbose common parameter. #> Function Write-CustomLog { [CmdletBinding(SupportsShouldProcess = $True)] Param ( [Parameter(Mandatory = $False)] [string]$LogPath, [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory = $True)] [string[]]$Message ) Begin { if ($LogPath) { if (!(Test-Path -Path $LogPath)) { New-Item -Path $LogPath -ItemType File | Out-Null $initMessage = @( "***************************************************************************************************", "$([DateTime]::Now) - Started processing", "***************************************************************************************************", "`n" ) Add-Content -Path $LogPath -Value $initMessage } } } Process { if ($PSCmdlet.ShouldProcess($LogPath, "Write log")) { $Message | ForEach-Object { $logEntry = "$([DateTime]::Now) - $_" if ($LogPath) { Add-Content -Path $LogPath -Value $logEntry } Write-Verbose $logEntry } } } End { } } |