The Logging Function
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
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