Public/New-Log.ps1
Function New-Log { <# .SYNOPSIS This takes in some parameters to make it easier to consistently log. .PARAMETER Level This indicates the level based on predefined types. Info, Warn, Err, Debug .PARAMETER LogFile This should be a file path to a file. .PARAMETER Message This is a string that will be printed to the log and screen. .EXAMPLE PS> New-Log -LogFile 'test.log' -Level ([LogLevel]::Info) -Message "Test" 20240525 04:46:34.4667: Test #> param( [Parameter(Mandatory=$False)] [string]$LogFile, [Parameter(Mandatory=$False)] [ValidateSet("Info", "Warn", "Err", "Debug")] [string]$Level, [Parameter(Mandatory=$True)] [string]$Message ) Try { # Format the Log $Time = Get-Date -AsUTC -Format 'yyyyMMdd hh:mm:ss.ffff' $OutMessage = "$Time`: $Message" # Write to the log file if ($LogFile) { $OutMessage | Out-File $LogFile } # Write to the screen Switch ($Level) { (Info) { Write-Output $OutMessage } (Warn) { Write-Warning $OutMessage } (Err) { Write-Error $OutMessage } (Debug) { Write-Debug $OutMessage } default { Write-Output $OutMessage } } } Catch { # We were unable to write out... Throw "Unable to complete log update.`r`n$_" } } |