The Logging Function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | function Write-Log { param ( [ Parameter ( Mandatory = $true )] [string] $message , [ Parameter ( Mandatory = $true )] [string] $logFilePath , [ Parameter ( Mandatory = $false )] [ ValidateSet ( "INFO" , "ERROR" )] [string] $logType = "INFO" ) # Get the current date and time $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" # Construct the log entry $logEntry = "$timestamp - $logType - $message" # Append the log entry to the log file try { Add-Content -Path $logFilePath -Value $logEntry # Display the log entry using Write-Output or Write-Error based on log type if ( $logType -eq "INFO" ) { Write-Output $message } else { Write-Error $message } } catch { Write-Error "Failed to write to the log file. Error: $_" } } |
Using the Logging Function
1 2 | Write-Log -message "This is an informational log entry." -logFilePath "C:\path\to\your\log.txt" -logType "INFO" Write-Log -message "This is an error log entry." -logFilePath "C:\path\to\your\log.txt" -logType "ERROR" |
0 Comments