======Microsoft - Scripting - PowerShell - Snippets - Logging====== Provides the following functions to log to a CSV file: * InitLog: to start an empty log if not previous log exists. * AppendToLog: to add a line to the CSV log. * Log-Info: to log and show an informational message. * Log-Warning: to log and show a warning message. * Log-Error: to log and show an error message. # When importing CSVs, what is the default delimiter? $strCsvDelimiter = ";" #$strScriptPath = Split-Path ((Get-Variable MyInvocation).Value).MyCommand.Path -Parent $strWorkingDir = ((Get-Variable PWD).Value).Path # Log settings. $strLogFile = "$strWorkingDir\Script-logfile.csv" # Function: Initialize the log with the CSV header. function InitLog() { if (-Not (Test-Path -Path "$strLogFile" -PathType Leaf)) { "DateTime" + $strCsvDelimiter + "User" + $strCsvDelimiter + "Status" + $strCsvDelimiter + "Message" | Out-File -FilePath "$strLogFile" } } # Function: Append a line to the logfile. function AppendToLog([string]$Message, [string]$Status) { $strDateTime = Get-Date -Format o $strDateTime + $strCsvDelimiter + $env:USERNAME + $strCsvDelimiter + $Status + $strCsvDelimiter + $Message | Out-File -FilePath "$strLogFile" -Append } # Function: Log and display an info message. function Log-Info([string]$Message) { AppendToLog -Message $Message -Status "INFO" Write-Host Write-Host $Message -ForeGroundColor Yellow } # Function: Log and display a warning message. function Log-Warning([string]$Message) { AppendToLog -Message $Message -Status "WARNING" Write-Host Write-Host $Message -ForeGroundColor Yellow } # Function: Log and display an error message. function Log-Error([string]$Message) { AppendToLog -Message $Message -Status "ERROR" Write-Host Write-Host $Message -ForeGroundColor Red }