Logging Function v2.0
As I created an earlier post with a simple logging function in poweshell, a while ago I upgraded this with a specific Error, Success and info switch. This way I can put it with simple colors as output on screen to see if something goes wrong or good. And also logging will be better searchable.
$Logfile = "D:\LogFile.txt" Function LogWrite{ <# <span style="font-size: 0.95em; line-height: 1.6em;">.SYNOPSIS This functions is used to generate a log file </span><span style="font-size: 0.95em; line-height: 1.6em;">.DESCRIPTION Function creates output on screen depending on given switch and writes this with error code to the logfile .PARAMETER $Logstring Location to the logfile .PARAMETER $Error Switch to identify an error message .PARAMETER $Success Switch to identify a success message .PARAMETER $Info Switch to identify an info message .EXAMPLE PS C:\> Logwrite -error "This is an error" </span> .INPUTS System.String,System.Switch .OUTPUTS System.String #> [CmdletBinding()] [OutputType([System.String])] Param( [string]$Logstring, [switch]$Error, [switch]$Success, [switch]$Info ) try { if ($Error){ $logstring = (Get-Date).ToString() + " ERROR: " + $logstring Write-Host -ForegroundColor red $logstring } elseif ($Success){ $logstring = (Get-Date).ToString() + " SUCCESS: " + $logstring Write-Host -ForegroundColor green $logstring } elseif ($Info){ $logstring = (Get-Date).ToString() + " INFO: " + $logstring Write-Host $logstring } else { $logstring = (Get-Date).ToString() + " INFO: " + $logstring Write-Host $logstring } Add-content $Logfile -value $logstring } catch { throw } } #Example logwrite -success "Success creating user: $user" logwrite -error "Error creating user $user" logwrite -info"Success quering user: $user"