Private/Write-Log.ps1
|
# Write-Log.ps1 # Writes timestamped entries to console and log file. # Part of the M365-QuickAssess module -- not exported. function Write-Log { param ( [string]$Message, [ValidateSet("INFO","WARN","ERROR")] [string]$Level = "INFO" ) try { # ------------------------------------------------------------------- # Ensure output directory exists # ------------------------------------------------------------------- $outputPath = $script:Context.OutputPath if ( -not $outputPath ) { $outputPath = "C:\ProgramData\Rackspace-Technology" } if ( -not ( Test-Path $outputPath -ErrorAction SilentlyContinue ) ) { New-Item -ItemType Directory -Path $outputPath -Force -ErrorAction SilentlyContinue | Out-Null } # ------------------------------------------------------------------- # Don't write to file until tenant context is established # ------------------------------------------------------------------- $prefix = $script:Context.TenantPrefix $label = $script:Context.WorkloadLabel $stamp = $script:Context.RunStamp # ------------------------------------------------------------------- # Format entry # ------------------------------------------------------------------- $timestamp = ( Get-Date ).ToString("yyyy-MM-dd HH:mm:ss") $entry = "[$timestamp][$Level] $Message" # Console output with color coding by level switch ( $Level ) { "ERROR" { Write-Host $entry -ForegroundColor Red } "WARN" { Write-Host $entry -ForegroundColor Yellow } default { Write-Host $entry } } # File output -- only once tenant context is established if ( $prefix -and $stamp ) { $logFile = Join-Path $outputPath "$prefix-$label-$stamp.log" Add-Content -Path $logFile -Value $entry -ErrorAction SilentlyContinue } } catch { # Last resort -- if everything else fails just write to console Write-Host "[$Level] $Message" } } |