function Write-WinUtilLog { <# .SYNOPSIS Writes a timestamped WinUtil log entry to the active session log. .PARAMETER Message The message to write. .PARAMETER Level The severity level for the log entry. .PARAMETER Component The WinUtil component producing the log entry. #> param ( [Parameter(Mandatory = $true)] [string]$Message, [ValidateSet("INFO", "WARN", "ERROR", "DEBUG")] [string]$Level = "INFO", [string]$Component = "WinUtil" ) try { $logPath = $null $transcriptPath = $null if ($null -ne $sync -and $sync.ContainsKey("logPath")) { $logPath = $sync.logPath } if ($null -ne $sync -and $sync.ContainsKey("transcriptPath")) { $transcriptPath = $sync.transcriptPath } if ([string]::IsNullOrWhiteSpace($logPath) -and -not [string]::IsNullOrWhiteSpace($transcriptPath)) { $logPath = $transcriptPath } if ([string]::IsNullOrWhiteSpace($logPath) -and $null -ne $sync -and $sync.ContainsKey("winutildir")) { $logDirectory = Join-Path $sync.winutildir "logs" $logPath = Join-Path $logDirectory "winutil_$(Get-Date -Format "yyyy-MM-dd_HH-mm-ss").log" $sync.logPath = $logPath } if ([string]::IsNullOrWhiteSpace($logPath) -and -not [string]::IsNullOrWhiteSpace($env:LocalAppData)) { if ([string]::IsNullOrWhiteSpace($script:WinUtilLogPath)) { $logDirectory = Join-Path (Join-Path $env:LocalAppData "winutil") "logs" $script:WinUtilLogPath = Join-Path $logDirectory "winutil_$(Get-Date -Format "yyyy-MM-dd_HH-mm-ss").log" } $logPath = $script:WinUtilLogPath } if ([string]::IsNullOrWhiteSpace($logPath)) { return } $logDirectory = Split-Path -Path $logPath -Parent if (-not (Test-Path $logDirectory)) { New-Item -Path $logDirectory -ItemType Directory -Force | Out-Null } $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss.fff" $line = "[$timestamp] [$Level] [$Component] $Message" if (-not [string]::IsNullOrWhiteSpace($transcriptPath) -and $logPath -eq $transcriptPath) { Write-Host $line return } try { Add-Content -Path $logPath -Value $line -Encoding UTF8 -ErrorAction Stop } catch [System.IO.IOException] { Write-Host $line } } catch { Write-Warning "Unable to write WinUtil log entry: $($_.Exception.Message)" } }