Last active
March 25, 2024 11:06
-
-
Save dancing-groot/6af20a68e67306762905665db339d30d to your computer and use it in GitHub Desktop.
Function for writing to a log file in plain format, with the option to write the information to the host as well
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[CmdletBinding()] | |
param() | |
#region FUNCTIONS | |
function Write-SimpleLog | |
{ | |
<# | |
.SYNOPSIS | |
Write information to a log file and optionally to the console | |
.LINK | |
https://gist.github.com/dancing-groot/6af20a68e67306762905665db339d30d | |
.NOTES | |
Version: 2022.12.09 | |
Author: @dancing-groot | |
#> | |
[cmdletbinding()] | |
param ( | |
[string]$Path = "$($ENV:TEMP)\$(Get-Date -UFormat '%Y.%m.%d').log", | |
[parameter(Mandatory = $true)] | |
[string]$Message, | |
[ValidateSet('Warning', 'Error', 'Verbose', 'Debug', 'Information', 'Info')] | |
[string]$Type = "Info", | |
[switch]$WriteBackToHost = $false | |
) | |
if ($Type -eq "Information") { $Type = "Info" } | |
$content = "$(Get-Date -UFormat '%Y.%m.%d %T')" + "`t" + ` | |
$Type + "`t" + ` | |
$Message | |
# Write the line to the log file | |
Add-Content -Path $Path -Value $content | |
if ($WriteBackToHost) | |
{ | |
switch ($Type) | |
{ | |
"Info" { Write-Information $Message -InformationAction Continue; break } | |
"Warning" { Write-Warning $Message -WarningAction Continue; break } | |
"Error" { Write-Host "ERROR: $Message" -ForegroundColor Red; break } | |
"Verbose" { Write-Verbose $Message; break } | |
"Debug" { Write-Debug $Message; break } | |
} | |
} | |
} # Write-SimpleLog | |
#endregion FUNCTIONS | |
#region DECLARATION | |
$LogName = ($MyInvocation.MyCommand.Name).TrimEnd(".ps1") | |
$LogFile = "$PSScriptRoot\$LogName.log" | |
if (Test-Path (Split-Path $LogFile -Parent) -eq $false) {New-Item -Path (Split-Path $LogFile -Parent) -Type Directory} | |
$LogParams = @{Path = $LogFile; WriteBackToHost = $true } # Messages will be written to the log and to the prompt | |
#endregion DECLARATION | |
#region TESTING | |
Write-SimpleLog @LogParams -Message "This is an Information message" | |
Write-SimpleLog @LogParams -Message "This is a Debug message" -Type Debug | |
Write-SimpleLog @LogParams -Message "This is a Verbose message" -Type Verbose | |
Write-SimpleLog @LogParams -Message "This is a Warning message" -Type Warning | |
Write-SimpleLog @LogParams -Message "This is an Error message" -Type Error | |
#region TESTING |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment