I have written a logging function for my PowerShell Script, which will log the Input to the file, at the same time also display the same onto the output screen. While displaying the output on the screen, depending on different matching conditions, the Output will be displayed in different colors. I have used switch statement to compare the input to a set of conditions and then display the output.
However I feel that this approach is not efficient, considering there are over 20 condition that are to be met, each will have its own formatting. Can anyone suggest an alternative approach or any optimal change that can be done in this approach ?
Below is a sample code :
[String] WriteLog([string]$LogString)
{
#Logging to File
If (!(Test-Path $this.LogFile)) {New-Item -Path $this.LogFile -Force}
Add-content $this.LogFile -value $LogString
#Printing on Console
switch -CaseSensitive -Wildcard ($LogString)
{
'*PASSED*'
{
Write-host $LogString -fore Green -nonewline
break
}
'*Warnings.*'
{
Write-host $LogString -fore Yellow -nonewline
break
}
'*Fail*'
{
Write-host $LogString -fore Red-nonewline
break
}
'*Run*'
{
Write-Host $LogString -NoNewline -fore Red -BackgroundColor White -nonewline
}
default
{
Write-Host " " $LogString
}
}
}
If you would have just a wildcard string to check and a foreground color depending on the wildcard, you could use a hashtable with key & value:
In your case you have also a background color depending to the wildcard string, so as an alternative to your switch statement you could use a psobject array: