PowerShell Custom Log function

Veröffentlicht am: 20 August 2020
auf dem Kanal: 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


Auf dieser Seite können Sie das Online-Video PowerShell Custom Log function mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer Mr Automation 20 August 2020 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 1,780 Mal angesehen und es wurde von 25 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!