PowerShell Custom Log function

Published: 20 August 2020
on channel: Mr Automation
1,780
25

*How to create your own logging function in powershell
*powershell log function
*write-host with colors

In this video I show you how you can add some nice logging into your powershell code.

Code :
#Modules file created by Mark Bakker, this is module for logging purposes, like writing to file, console and sending mail
Function Write-MRBMessage {
Param(
[Parameter(Mandatory = $true)] $Message,
[Parameter(Mandatory = $true)]
[ValidateSet('INFO','WARNING','ERROR')]
[string]$Category
#[Parameter(Mandatory = $true)] $LogFile
#[Parameter(Mandatory = $false)][boolean]$NoNewLine = $true
)
Try {
$Date = ((Get-Date -f dd-MM-yyyy-HH:mm:ss).tostring())
$Cat = $Null
switch ($Category) {
"ERROR" {
$MessageColor = 'red'
$Cat = 'ERR'
}
"WARNING" {
$MessageColor = 'yellow'
$Cat = 'WAR'
}
"INFO" {
$MessageColor = 'Green'
$Cat = 'INF'
}
default {Write-Host "The category of the message could not be determined" -ForegroundColor Red -BackgroundColor Black}
}

Write-Host -Object "[" -NoNewline -ForegroundColor Cyan
Write-Host -Object $Date -NoNewline -ForegroundColor White
Write-Host -Object "]" -NoNewline -ForegroundColor Cyan
Write-Host -Object " - " -NoNewline -ForegroundColor Green

Write-Host -Object "[" -NoNewline -ForegroundColor Cyan
Write-Host -Object $Cat -NoNewline -ForegroundColor White
Write-Host -Object "]" -NoNewline -ForegroundColor Cyan

Write-Host -Object " - " -NoNewline -ForegroundColor Green
Write-Host -Object "[" -NoNewline -ForegroundColor Cyan
Write-Host -Object $Message -NoNewline -ForegroundColor $MessageColor

if ($NoNewLine) {
Write-Host -Object "]" -ForegroundColor Cyan -NoNewline
}
else {
Write-Host -Object "]" -ForegroundColor Cyan
}

#$Message = $Date + " " + $Message
#Out-File $LogFile -encoding ASCII -input $message -append

$Date = $Null
$Message = $Null
$MessageColor = $Null
}
Catch {
Write-Host "ERROR While trying to write message : $($_.Exception.Message), SCRIPT QUITS with ERROR -1 !!" -BackgroundColor Black -ForegroundColor Red
}
}

Write-MRBMessage -Message "this is a info message" -Category INFO
Write-MRBMessage -Message "this is a warning message" -Category WARNING
Write-MRBMessage -Message "this is a error message" -Category ERROR


On this page of the site you can watch the video online PowerShell Custom Log function with a duration of hours minute second in good quality, which was uploaded by the user Mr Automation 20 August 2020, share the link with friends and acquaintances, this video has already been watched 1,780 times on youtube and it was liked by 25 viewers. Enjoy your viewing!