Skip to content

Instantly share code, notes, and snippets.

@MattMatheus
Created December 2, 2019 20:22
Show Gist options
  • Select an option

  • Save MattMatheus/3c27393b0427d791f1cc391d755e13d6 to your computer and use it in GitHub Desktop.

Select an option

Save MattMatheus/3c27393b0427d791f1cc391d755e13d6 to your computer and use it in GitHub Desktop.
<#
.EXAMPLE
Write-Log -Message "This is default info message"
Write-Log -Message "This is error message" -Level "ERROR"
#>
function Write-Log {
Param (
[Parameter(Mandatory=$true)]
[string]$message,
[Parameter(Mandatory=$false)]
[string]$logpath='C:\logs\logfile.log',
[Parameter(Mandatory=$false)]
[ValidateSet("Error", "Warn", "Info")]
[string]$level="Info"
)
Begin {
#Set verbose preference to continue so we can receive verbose messages
$VerbosePreference = 'Continue'
}
Process {
if(!(Test-Path $logpath)) {
Write-Verbose "Creating $logpath."
$NewLogFile = New-Item $logpath -Force -ItemType File
}
$FormattedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
#write the log entry
"$FormattedDate [$level] $Message" | Out-File -FilePath $logpath -Append
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment