Fix session log missing everything after the window opens (#5210)

* Write the session log from every runspace instead of a transcript

The session log was a Start-Transcript on the main thread, and
Write-WinUtilLog wrote through the host so the transcript would pick its
lines up. A transcript only records the runspace that started it, though,
so everything logged from the UI thread or a job worker went to the
console and never reached the file. An exported log stopped at "Starting
the interface thread." no matter what happened afterwards.

Write-WinUtilLog now appends through one writer kept in $sync, opened on
first use and flushed on every line, so any runspace can log to the same
file. Other processes can still read it while it is open, which the
environment report's log bundle relies on. Close-WinUtilLog releases it
on both exits in place of Stop-Transcript, and the first entry records
the WinUtil, PowerShell and Windows versions the transcript header used
to carry. The console echo goes through Write-WinUtilHost.

* Write banners, progress and error lines straight to the host

Write-Host also emits an information record, so anything that collects a
runspace's Write-Host output into the log would pick these up as well:
a boxed banner per job, a line for every progress frame, and a second
copy of an error Write-WinUtilErrorRecord has already logged. They are
console-only, so they now go through Write-WinUtilHost, which writes to
the host directly and looks the same on screen.

* Log Write-Host output from job bodies

The job layer already merged a body's warning and error streams into its
output so they reached the log, but Write-Host went to the console only.
Tweaks, services, registry and DNS changes all report what they did with
Write-Host, so none of "Set ... to ..." or "Setting Service ..." ever
made it into the file.

The body's information stream is merged too, and every record goes to
Write-WinUtilStreamRecord. Write-Host lines are logged and shown again
with their original colours, since redirecting them takes them off the
console. Warnings and non-terminating errors are logged as before.

* Log the UI thread's output while the window is open

The UI runspace's warnings and errors collect on its PowerShell object.
Main logged them only after the window closed, too late for a report
exported during the session, and never logged its Write-Host output,
which is what toggles report through.

The main thread has nothing to do while the window is open, so instead
of blocking it now wakes every 250 ms and moves those streams into the
log, then empties them once more after the window closes. Warnings and
Write-Host lines are already on the console, so they are only written
to the file. Non-terminating errors were never shown, so they are
printed too.

* Describe the new session log wiring in the architecture docs

The logging section said Write-WinUtilLog wrote through the host so a
transcript could capture it, and the threading example showed the main
thread blocking on the window. Both have changed: every thread writes
the file through one shared writer, jobs and the main thread collect
Write-Host output, warnings and errors into it, and banners and progress
use Write-WinUtilHost to stay out of it.

* Replace the transcript logging rule in AGENTS.md

The old rule told agents to write through the host so Start-Transcript
would capture log lines. That is what lost every entry from the UI
thread and the jobs. The rule now says not to use a transcript for the
session log, to log through Write-WinUtilLog, and to use
Write-WinUtilHost for console-only output.

* Write the session log with a UTF-8 BOM

Windows PowerShell 5.1's Get-Content reads a file without a BOM as the
system ANSI code page. The log was written as BOM-less UTF-8, so the
environment report's log bundle turned any non-ASCII text, such as
localized warnings, package names or user paths, into mojibake.

The writer now emits the BOM, as Add-Content -Encoding UTF8 did on 5.1
before. StreamWriter only writes it to an empty file, so reopening the
log after Close-WinUtilLog does not put a second one mid-file.

* Describe the session log in SPEC.md's runtime model

The runtime model covered runspaces and $sync but said nothing about
logging. It now records that every runspace logs through
Write-WinUtilLog's shared writer, that job output and the UI runspace's
streams are collected into the session file, and that console-only
output uses Write-WinUtilHost.
This commit is contained in:
Sean (ANGRYxScotsman) authored and GitHub committed 2026-10-30 13:48:01 -05:00
1 parent 418a60cb55
commit b521c90ea5
15 files changed
+498 -149

No files matched your search

+1 -1
View File
@@ -176,7 +176,7 @@ When the user corrects an agent approach, add or tighten one concrete rule here
- Keep WinUtil runtime logging in the existing timestamped `%LocalAppData%\winutil\logs\winutil_*.log` session file; do not create a separate root `winutil.log`.
- Import Pester 5.8.0 before running tests so `Invoke-Pester -Output Detailed -CI` does not resolve to Windows' inbox Pester 3.4.0.
- Keep package install/uninstall process launches simple unless explicitly requested; do not add a separate stdout/stderr process logging helper for winget or Chocolatey.
- When the active log file is owned by `Start-Transcript`, do not call `Add-Content` against that file; write to host output so the transcript captures the line in the same log file without recording a terminating-error diagnostic.
- Do not use `Start-Transcript` for the session log; it only records the runspace that started it, so the UI thread and jobs never reached the file. Log through `Write-WinUtilLog`, and use `Write-WinUtilHost` rather than `Write-Host` for console-only output such as banners and progress.
- Keep UI helpers such as `Invoke-WPFUIThread` and `Step-WinUtilJob` safe to call without a window; the `-Preset` and `-Config` paths run the workflows before the form is created and before PresentationCore is loaded. Ask `Test-WinUtilUIAlive` rather than writing the `$sync.Form` / dispatcher / `HasShutdownStarted` check out by hand.
- Put long operations on the job layer with `Start-WinUtilJob` and report from them with `Step-WinUtilJob`; a job body must not set the busy flag, print its own banner, or carry its own try/catch/finally around the interface. `Invoke-WPFRunspace` directly is for fire-and-forget work that is not a job.
- Drain interface work that nobody is waiting for through `Start-WinUtilBackgroundQueue`; do not hand-roll another dequeue-and-re-post pump.
+1
View File
@@ -70,6 +70,7 @@ Because the final script is concatenated, code cannot rely on runtime module imp
- Shared mutable state is stored in `$sync`, including configs, UI element references, runspace state, selections, and progress.
- Long-running operations use runspaces or existing async patterns so the UI remains responsive.
- UI updates from background work are dispatched back to the WPF UI thread.
- Every runspace logs to the timestamped `%LocalAppData%\winutil\logs` session file through `Write-WinUtilLog`, which shares one writer through `$sync`. Job output and the UI runspace's warnings, errors and `Write-Host` output are collected into it; console-only output such as banners and progress uses `Write-WinUtilHost`.
- Declarative features such as apps, tweaks, presets, DNS providers, and navigation stay in `config/*.json` unless code is required.
## UI And Event Contract
@@ -439,7 +439,9 @@ $uiShell = [powershell]::Create()
$uiShell.Runspace = $sync.UIRunspace
[void]$uiShell.AddScript({ Start-WinUtilUserInterface })
$uiHandle = $uiShell.BeginInvoke()
$uiHandle.AsyncWaitHandle.WaitOne()
while (-not $uiHandle.AsyncWaitHandle.WaitOne(250)) {
Receive-WinUtilStreamOutput -PowerShell $uiShell -Component "UI"
}
```
**Why**: the window never blocks on work, and a failure on the interface thread is reported
@@ -533,10 +535,10 @@ such as cleaning up a mounted image, and then rethrow.
Write-WinUtilLog -Level "ERROR" -Component "Install" -Message "winget install failed: $($_.Exception.Message)"
```
Entries and console diagnostics go to the same
`%LocalAppData%\winutil\logs\winutil_<timestamp>.log` session file. While `Start-Transcript`
owns that file, `Write-WinUtilLog` writes through the host so the transcript captures the entry
without a competing direct file write.
Every thread writes to the same `%LocalAppData%\winutil\logs\winutil_<timestamp>.log` session
file through one shared writer. `Start-WinUtilJob` logs a job's warnings, errors and `Write-Host`
output, and the main thread logs the interface thread's while the window is open. Banners and
progress go through `Write-WinUtilHost` instead of `Write-Host` so they stay out of the log.
## Configuration Loading
+4 -6
View File
@@ -120,15 +120,13 @@ function Start-WinUtilJob {
try {
$body = [scriptblock]::Create($JobBody)
# A worker's warning and error streams buffer on a PowerShell object nobody reads.
# Merging them into the output stream is what gets them to the log.
& $body @JobParameters 2>&1 3>&1 | ForEach-Object {
# A worker's warning, error and Write-Host output buffers on a PowerShell object
# nobody reads. Merging it into the output stream is what gets it to the log.
& $body @JobParameters 2>&1 3>&1 6>&1 | ForEach-Object {
if ($_ -is [System.Management.Automation.WarningRecord]) {
$global:WinUtilJobWarningCount++
Write-WinUtilLog -Level "WARN" -Component $JobName -Message $_.Message
} elseif ($_ -is [System.Management.Automation.ErrorRecord]) {
Write-WinUtilErrorRecord -ErrorRecord $_ -Component $JobName -Context "Non-terminating error"
}
Write-WinUtilStreamRecord -Record $_ -Component $JobName
}
$jobClock.Stop()
@@ -58,13 +58,13 @@ function Write-WinUtilConsoleProgress {
$line = "$prefix$text"
if ($redirected) {
Write-Host $line -ForegroundColor DarkCyan
Write-WinUtilHost $line -ForegroundColor DarkCyan
return
}
# Pad to the previous length so a shorter line does not leave the tail of the longer one
$padding = [Math]::Max(0, $state.LineLength - $line.Length)
Write-Host ("`r$line" + (" " * $padding)) -NoNewline -ForegroundColor DarkCyan
Write-WinUtilHost ("`r$line" + (" " * $padding)) -NoNewline -ForegroundColor DarkCyan
$state.LineLength = $line.Length
$state.LineOpen = $true
}
@@ -84,7 +84,7 @@ function Complete-WinUtilConsoleProgress {
return
}
Write-Host ""
Write-WinUtilHost ""
$state.LineOpen = $false
$state.LineLength = 0
$state.LastText = ""
@@ -53,6 +53,6 @@ function Write-WinUtilErrorRecord {
}
if (-not $DetailOnly) {
Write-Host "$Component : $headline" -ForegroundColor Red
Write-WinUtilHost "$Component : $headline" -ForegroundColor Red
}
}
+4 -4
View File
@@ -45,10 +45,10 @@ function Write-WinUtilJobBanner {
$border = "=" * ($longest + 6)
$colour = if ($Level -eq "ERROR") { "Red" } else { "Cyan" }
Write-Host ""
Write-Host $border -ForegroundColor $colour
Write-WinUtilHost ""
Write-WinUtilHost $border -ForegroundColor $colour
foreach ($line in $lines) {
Write-Host ("-- {0}$(' ' * ($longest - $line.Length)) --" -f $line) -ForegroundColor $colour
Write-WinUtilHost ("-- {0}$(' ' * ($longest - $line.Length)) --" -f $line) -ForegroundColor $colour
}
Write-Host $border -ForegroundColor $colour
Write-WinUtilHost $border -ForegroundColor $colour
}
+179 -88
View File
@@ -1,24 +1,4 @@
function Write-WinUtilLog {
<#
.SYNOPSIS
Writes a timestamped WinUtil log entry to the active session log.
.DESCRIPTION
Called from the interface thread and from every job body. When Start-Transcript owns the
active session log, entries go through the host so the transcript records them without a
competing file write. Standalone callers use a named mutex to serialize direct appends.
.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,
@@ -29,11 +9,13 @@ function Write-WinUtilLog {
[string]$Component = "WinUtil",
# Continuation of an error already counted, such as a stack frame
[switch]$Detail
[switch]$Detail,
[switch]$FileOnly
)
# UI performance diagnostics are useful to developers but are too noisy for the release
# transcript. Compile.ps1 stamps local builds so DEBUG output cannot leak into CI artifacts.
# log. Compile.ps1 stamps local builds so DEBUG output cannot leak into CI artifacts.
if ($Level -eq "DEBUG" -and ($null -eq $sync -or -not $sync.IsLocalCompile)) {
return
}
@@ -49,77 +31,186 @@ function Write-WinUtilLog {
$global:WinUtilJobErrorCount++
}
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss.fff"
$line = "[$timestamp] [$Level] [$Component] $Message"
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
}
$mutex = [System.Threading.Mutex]::new($false, "WinUtilSessionLog")
$held = $false
try {
$writer = Get-WinUtilLogWriter
if ($null -ne $writer) {
[System.Threading.Monitor]::Enter($writer)
try {
$held = $mutex.WaitOne(2000)
} catch [System.Threading.AbandonedMutexException] {
# A thread died holding the mutex; ownership transfers to us either way
$held = $true
$writer.WriteLine($line)
} finally {
[System.Threading.Monitor]::Exit($writer)
}
if (-not $held) {
# Writing anyway is what interleaves lines, and the wait only times out when
# contention is at its worst
Write-Host $line
return
}
Add-Content -Path $logPath -Value $line -Encoding UTF8 -ErrorAction Stop
} catch [System.IO.IOException] {
Write-Host $line
} finally {
if ($held) { $mutex.ReleaseMutex() }
$mutex.Dispose()
}
} catch [System.IO.IOException] {
Write-Verbose "Unable to write WinUtil log entry: $($_.Exception.Message)"
} catch {
Write-Warning "Unable to write WinUtil log entry: $($_.Exception.Message)"
}
if (-not $FileOnly) {
Write-WinUtilHost $line
}
}
# Opens the session log once for every runspace to share. Others can still read it, e.g. the environment report.
function Get-WinUtilLogWriter {
$state = $sync
if ($null -eq $state) {
if ([string]::IsNullOrWhiteSpace($env:LocalAppData)) {
return $null
}
if ($null -eq $script:WinUtilLogState) {
$script:WinUtilLogState = [hashtable]::Synchronized(@{
winutildir = Join-Path $env:LocalAppData "winutil"
})
}
$state = $script:WinUtilLogState
}
$writer = $state.LogWriter
if ($null -ne $writer -and $state.LogWriterPath -eq $state.logPath) {
return $writer
}
[System.Threading.Monitor]::Enter($state.SyncRoot)
try {
if ([string]::IsNullOrWhiteSpace($state.logPath)) {
if ([string]::IsNullOrWhiteSpace($state.winutildir)) {
return $null
}
$state.logPath = Join-Path (Join-Path $state.winutildir "logs") "winutil_$(Get-Date -Format "yyyy-MM-dd_HH-mm-ss").log"
}
if ($null -ne $state.LogWriter -and $state.LogWriterPath -eq $state.logPath) {
return $state.LogWriter
}
if ($null -ne $state.LogWriter) {
$state.LogWriter.Dispose()
$state.LogWriter = $null
}
$logDirectory = Split-Path -Path $state.logPath -Parent
if (-not (Test-Path -LiteralPath $logDirectory)) {
New-Item -Path $logDirectory -ItemType Directory -Force | Out-Null
}
$stream = [System.IO.FileStream]::new(
$state.logPath,
[System.IO.FileMode]::Append,
[System.IO.FileAccess]::Write,
[System.IO.FileShare]::Read)
$newWriter = [System.IO.StreamWriter]::new($stream, [System.Text.UTF8Encoding]::new($true))
$newWriter.AutoFlush = $true
$state.LogWriterPath = $state.logPath
$state.LogWriter = $newWriter
return $newWriter
} finally {
[System.Threading.Monitor]::Exit($state.SyncRoot)
}
}
# Lets go of the log file when WinUtil exits, so the terminal it ran in doesn't keep it locked
function Close-WinUtilLog {
$state = if ($null -ne $sync) { $sync } else { $script:WinUtilLogState }
if ($null -eq $state -or $null -eq $state.LogWriter) {
return
}
$writer = $state.LogWriter
[System.Threading.Monitor]::Enter($writer)
try {
$state.LogWriter = $null
$state.LogWriterPath = $null
$writer.Dispose()
} finally {
[System.Threading.Monitor]::Exit($writer)
}
}
# Console-only output like banners and progress. Unlike Write-Host, a job won't log it.
function Write-WinUtilHost {
param(
[string]$Object = "",
[Nullable[System.ConsoleColor]]$ForegroundColor,
[Nullable[System.ConsoleColor]]$BackgroundColor,
[switch]$NoNewline
)
$rawUI = $Host.UI.RawUI
if ($null -eq $rawUI -or ($null -eq $ForegroundColor -and $null -eq $BackgroundColor)) {
if ($NoNewline) {
$Host.UI.Write($Object)
} else {
$Host.UI.WriteLine($Object)
}
return
}
$foreground = if ($null -ne $ForegroundColor) { $ForegroundColor } else { $rawUI.ForegroundColor }
$background = if ($null -ne $BackgroundColor) { $BackgroundColor } else { $rawUI.BackgroundColor }
if ($NoNewline) {
$Host.UI.Write($foreground, $background, $Object)
} else {
$Host.UI.WriteLine($foreground, $background, $Object)
}
}
# Logs a warning, error or Write-Host record from another runspace, and shows it too unless -Shown says it already was
function Write-WinUtilStreamRecord {
param(
[Parameter(Mandatory)]
$Record,
[string]$Component = "WinUtil",
[switch]$Shown
)
if ($Record -is [System.Management.Automation.WarningRecord]) {
Write-WinUtilLog -Level "WARN" -Component $Component -Message $Record.Message -FileOnly:$Shown
} elseif ($Record -is [System.Management.Automation.ErrorRecord]) {
Write-WinUtilErrorRecord -ErrorRecord $Record -Component $Component -Context "Non-terminating error"
} elseif ($Record -is [System.Management.Automation.InformationRecord]) {
$message = $Record.MessageData
if (-not $Shown -and $message -is [System.Management.Automation.HostInformationMessage]) {
Write-WinUtilHost -Object $message.Message -ForegroundColor $message.ForegroundColor `
-BackgroundColor $message.BackgroundColor -NoNewline:([bool]$message.NoNewLine)
}
$text = "$message".TrimEnd()
if ($text) {
Write-WinUtilLog -Component $Component -Message $text -FileOnly
}
}
}
# Logs and clears a runspace's warnings, errors and Write-Host output. Never throws, as the main thread runs it.
function Receive-WinUtilStreamOutput {
param(
[Parameter(Mandatory)]
$PowerShell,
[string]$Component = "WinUtil"
)
try {
foreach ($record in $PowerShell.Streams.Information.ReadAll()) {
Write-WinUtilStreamRecord -Record $record -Component $Component -Shown
}
foreach ($record in $PowerShell.Streams.Warning.ReadAll()) {
Write-WinUtilStreamRecord -Record $record -Component $Component -Shown
}
foreach ($record in $PowerShell.Streams.Error.ReadAll()) {
Write-WinUtilStreamRecord -Record $record -Component $Component
}
} catch {
Write-Warning "Unable to log $Component output: $($_.Exception.Message)"
}
}
+2 -2
View File
@@ -173,8 +173,8 @@ exit 23
}
It "cleans up even when the run throws" {
# Without a finally a failed run leaves the worker pool open and the transcript running
$script:mainScript | Should -Match '\} finally \{[\s\S]*Close-WinUtilRunspacePool[\s\S]*Stop-Transcript'
# Without a finally a failed run leaves the worker pool open and the log file held
$script:mainScript | Should -Match '\} finally \{[\s\S]*Close-WinUtilRunspacePool[\s\S]*Close-WinUtilLog'
}
It "names the presets that exist when given one that does not" {
+26 -1
View File
@@ -4,6 +4,7 @@
BeforeAll {
$script:repoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
. (Join-Path $script:repoRoot "functions\private\Measure-WinUtilStep.ps1")
. (Join-Path $script:repoRoot "functions\private\Write-WinUtilLog.ps1")
. (Join-Path $script:repoRoot "functions\private\Write-WinUtilErrorRecord.ps1")
. (Join-Path $script:repoRoot "functions\private\Complete-WinUtilPackageRun.ps1")
. (Join-Path $script:repoRoot "functions\private\Start-WinUtilJob.ps1")
@@ -17,7 +18,7 @@ BeforeAll {
param([string]$Message, [string]$Level)
}
function Write-WinUtilLog {
param($Message, $Level, $Component, [switch]$Detail)
param($Message, $Level, $Component, [switch]$Detail, [switch]$FileOnly)
}
function Step-WinUtilJob {
param([string]$Status, [int]$Percent, [string]$State, [string]$Overlay, [switch]$Hide)
@@ -434,6 +435,30 @@ Describe "Start-WinUtilJob" {
$script:sync.LastJobResult.Errors | Should -Be 0
}
It "logs Write-Host output from the body and the helpers it calls" {
Mock Write-WinUtilHost { }
Start-WinUtilJob -Name "Tweaks" -ScriptBlock { } | Out-Null
& $script:capturedRunspaceBody `
-JobName "Tweaks" `
-JobLabel "Running tweaks" `
-JobBody 'function Set-Example { Write-Host "Set HKLM:\Example to 1" -ForegroundColor Green }; Write-Host "Running Script for WPFTweaksExample"; Set-Example' `
-JobParameters @{} `
-JobRestoresAppList $false `
-JobToken $script:capturedRunspaceArgs["JobToken"]
Should -Invoke -CommandName Write-WinUtilLog -Times 1 -Exactly -ParameterFilter {
$Component -eq "Tweaks" -and $Message -eq "Running Script for WPFTweaksExample" -and $FileOnly
}
Should -Invoke -CommandName Write-WinUtilLog -Times 1 -Exactly -ParameterFilter {
$Component -eq "Tweaks" -and $Message -eq "Set HKLM:\Example to 1" -and $FileOnly
}
Should -Invoke -CommandName Write-WinUtilHost -Times 1 -Exactly -ParameterFilter {
$Object -eq "Set HKLM:\Example to 1" -and $ForegroundColor -eq "Green"
}
$script:sync.LastJobResult.Warnings | Should -Be 0
}
It "finishes with a warning when elevated install skips a user-scoped package" {
Start-WinUtilJob -Name "Install" -ScriptBlock { } | Out-Null
+255 -17
View File
@@ -5,6 +5,9 @@ BeforeAll {
$script:repoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
. (Join-Path $script:repoRoot "functions\private\Write-WinUtilLog.ps1")
. (Join-Path $script:repoRoot "functions\private\Write-WinUtilErrorRecord.ps1")
. (Join-Path $script:repoRoot "functions\private\Write-WinUtilJobBanner.ps1")
. (Join-Path $script:repoRoot "functions\private\Write-WinUtilConsoleProgress.ps1")
. (Join-Path $script:repoRoot "functions\private\Measure-WinUtilStep.ps1")
}
@@ -12,12 +15,13 @@ Describe "Write-WinUtilLog" {
BeforeEach {
$script:testRoot = Join-Path ([System.IO.Path]::GetTempPath()) "winutil-logging-$([guid]::NewGuid())"
New-Item -Path $script:testRoot -ItemType Directory -Force | Out-Null
Remove-Variable -Name WinUtilLogPath -Scope Script -ErrorAction SilentlyContinue
Remove-Variable -Name WinUtilLogState -Scope Script -ErrorAction SilentlyContinue
}
AfterEach {
Close-WinUtilLog
Remove-Variable -Name sync -Scope Script -ErrorAction SilentlyContinue
Remove-Variable -Name WinUtilLogPath -Scope Script -ErrorAction SilentlyContinue
Remove-Variable -Name WinUtilLogState -Scope Script -ErrorAction SilentlyContinue
Remove-Variable -Name WinUtilIsJobWorker -Scope Global -ErrorAction SilentlyContinue
Remove-Variable -Name WinUtilJobErrorCount -Scope Global -ErrorAction SilentlyContinue
Remove-Item -Path $script:testRoot -Recurse -Force -ErrorAction SilentlyContinue
@@ -37,21 +41,114 @@ Describe "Write-WinUtilLog" {
Get-Content -Path $logPath -Raw | Should -Match "\[INFO\] \[Test\] same session log"
}
It "writes through the host when the transcript owns the active session log" {
It "records entries from a runspace that shares the console host" {
# Like the UI thread, which a transcript on the main thread never recorded
$logPath = Join-Path $script:testRoot "logs\winutil_2026-07-01_12-00-00.log"
$script:sync = [hashtable]::Synchronized(@{
logPath = $logPath
transcriptPath = $logPath
})
Mock Write-Host { }
Mock Add-Content { }
Write-WinUtilLog -Component "Test" -Message "transcript entry"
$initialSessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
$initialSessionState.Variables.Add(
(New-Object System.Management.Automation.Runspaces.SessionStateVariableEntry -ArgumentList "sync", $script:sync, $null)
)
$runspace = [runspacefactory]::CreateRunspace($Host, $initialSessionState)
$runspace.ApartmentState = "STA"
$runspace.Open()
$shell = [powershell]::Create()
$shell.Runspace = $runspace
Should -Invoke Write-Host -Times 1 -Exactly -ParameterFilter {
$Object -match "\[INFO\] \[Test\] transcript entry"
try {
[void]$shell.AddScript((Get-Content -Path (Join-Path $script:repoRoot "functions\private\Write-WinUtilLog.ps1") -Raw))
[void]$shell.AddScript("Write-WinUtilLog -Component 'UI' -Message 'from the interface thread'")
$shell.Invoke()
} finally {
$shell.Dispose()
$runspace.Dispose()
}
Should -Invoke Add-Content -Times 0 -Exactly
Write-WinUtilLog -Component "Test" -Message "from the main thread"
$content = Get-Content -Path $logPath
@($content | Where-Object { $_ -match "\[UI\] from the interface thread$" }).Count | Should -Be 1
@($content | Where-Object { $_ -match "\[Test\] from the main thread$" }).Count | Should -Be 1
}
It "keeps the session log readable while it is open" {
$logPath = Join-Path $script:testRoot "logs\winutil_2026-07-01_12-00-00.log"
$script:sync = [hashtable]::Synchronized(@{
logPath = $logPath
})
Write-WinUtilLog -Component "Test" -Message "first entry"
Get-Content -LiteralPath $logPath -Raw | Should -Match "first entry"
Write-WinUtilLog -Component "Test" -Message "second entry"
Get-Content -LiteralPath $logPath -Raw | Should -Match "second entry"
}
It "releases the file when closed and appends to it if a later entry arrives" {
$logPath = Join-Path $script:testRoot "logs\winutil_2026-07-01_12-00-00.log"
$script:sync = [hashtable]::Synchronized(@{
logPath = $logPath
})
Write-WinUtilLog -Component "Test" -Message "before close"
Close-WinUtilLog
$exclusive = [System.IO.File]::Open($logPath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
$exclusive.Dispose()
Write-WinUtilLog -Component "Test" -Message "after close"
$content = Get-Content -Path $logPath -Raw
$content | Should -Match "before close"
$content | Should -Match "after close"
}
It "marks the session log as UTF-8 once, even after reopening it" {
# Without a BOM, Windows PowerShell's Get-Content reads the log as ANSI and mangles non-ASCII text
$logPath = Join-Path $script:testRoot "logs\winutil_2026-07-01_12-00-00.log"
$script:sync = [hashtable]::Synchronized(@{
logPath = $logPath
})
Write-WinUtilLog -Component "Test" -Message "first session" -FileOnly
Close-WinUtilLog
Write-WinUtilLog -Component "Test" -Message "after reopening" -FileOnly
Close-WinUtilLog
$hex = [System.BitConverter]::ToString([System.IO.File]::ReadAllBytes($logPath)) -replace "-"
$hex | Should -BeLike "EFBBBF*"
([regex]::Matches($hex, "EFBBBF")).Count | Should -Be 1
}
It "shows the entry on the console without emitting a Write-Host record" {
$script:sync = [hashtable]::Synchronized(@{
logPath = Join-Path $script:testRoot "logs\winutil_2026-07-01_12-00-00.log"
})
Mock Write-WinUtilHost { }
# A Write-Host record here would get logged twice inside a job
$records = @(& { Write-WinUtilLog -Component "Test" -Message "console entry" } 6>&1)
$records.Count | Should -Be 0
Should -Invoke Write-WinUtilHost -Times 1 -Exactly -ParameterFilter {
$Object -match "\[INFO\] \[Test\] console entry"
}
}
It "writes only the file when the entry is already on the console" {
$logPath = Join-Path $script:testRoot "logs\winutil_2026-07-01_12-00-00.log"
$script:sync = [hashtable]::Synchronized(@{
logPath = $logPath
})
Mock Write-WinUtilHost { }
Write-WinUtilLog -Component "Test" -Message "collected output" -FileOnly
Should -Invoke Write-WinUtilHost -Times 0 -Exactly
Get-Content -Path $logPath -Raw | Should -Match "\[INFO\] \[Test\] collected output"
}
It "writes entries produced concurrently by several threads" {
@@ -110,22 +207,25 @@ Describe "Write-WinUtilLog" {
$content | Should -Match "second fallback entry"
}
It "falls back to host output when the log file cannot be opened" {
It "still shows the entry when the log file cannot be opened" {
$logPath = Join-Path $script:testRoot "logs\winutil_2026-07-01_12-00-00.log"
$script:sync = [hashtable]::Synchronized(@{
winutildir = $script:testRoot
logPath = $logPath
})
New-Item -Path (Split-Path -Path $logPath -Parent) -ItemType Directory -Force | Out-Null
$locked = [System.IO.File]::Open($logPath, [System.IO.FileMode]::OpenOrCreate, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
Mock Add-Content { throw [System.IO.IOException]::new("file is locked") } -ParameterFilter {
$Path -eq $logPath -and $ErrorAction -eq "Stop"
}
Mock Write-Host { }
Mock Write-WinUtilHost { }
Mock Write-Warning { }
Write-WinUtilLog -Component "Test" -Message "locked file fallback"
try {
Write-WinUtilLog -Component "Test" -Message "locked file fallback"
} finally {
$locked.Dispose()
}
Should -Invoke -CommandName Write-Host -Times 1 -Exactly -ParameterFilter {
Should -Invoke -CommandName Write-WinUtilHost -Times 1 -Exactly -ParameterFilter {
$Object -match "\[INFO\] \[Test\] locked file fallback"
}
Should -Invoke -CommandName Write-Warning -Times 0 -Exactly
@@ -202,3 +302,141 @@ Describe "Write-WinUtilLog" {
}
}
Describe "Collected runspace output" {
BeforeEach {
$script:testRoot = Join-Path ([System.IO.Path]::GetTempPath()) "winutil-logging-$([guid]::NewGuid())"
$script:logPath = Join-Path $script:testRoot "logs\winutil_2026-07-01_12-00-00.log"
$script:sync = [hashtable]::Synchronized(@{
logPath = $script:logPath
})
}
AfterEach {
Close-WinUtilLog
Remove-Variable -Name sync -Scope Script -ErrorAction SilentlyContinue
Remove-Variable -Name WinUtilJobErrorCount -Scope Global -ErrorAction SilentlyContinue
Remove-Item -Path $script:testRoot -Recurse -Force -ErrorAction SilentlyContinue
}
It "logs redirected Write-Host output and puts it back on the console as it was" {
Mock Write-WinUtilHost { }
& { Write-Host "Set HKLM:\Software\Example\Value to 1" -ForegroundColor Green } 6>&1 | ForEach-Object {
Write-WinUtilStreamRecord -Record $_ -Component "Tweaks"
}
Get-Content -Path $script:logPath -Raw | Should -Match "\[INFO\] \[Tweaks\] Set HKLM:\\Software\\Example\\Value to 1"
Should -Invoke Write-WinUtilHost -Times 1 -Exactly -ParameterFilter {
$Object -eq "Set HKLM:\Software\Example\Value to 1" -and $ForegroundColor -eq "Green"
}
}
It "logs redirected warnings and non-terminating errors" {
Mock Write-WinUtilHost { }
& { Write-Warning "Service Example was not found."; Write-Error "Access denied" } 2>&1 3>&1 | ForEach-Object {
Write-WinUtilStreamRecord -Record $_ -Component "Tweaks"
}
$content = Get-Content -Path $script:logPath -Raw
$content | Should -Match "\[WARN\] \[Tweaks\] Service Example was not found\."
$content | Should -Match "\[ERROR\] \[Tweaks\] Non-terminating error : Access denied"
}
It "does not show again what the host already displayed" {
Mock Write-WinUtilHost { }
$collected = @(& { Write-Host "toggle applied"; Write-Warning "toggle warning" } 3>&1 6>&1)
foreach ($record in $collected) {
Write-WinUtilStreamRecord -Record $record -Component "UI" -Shown
}
Should -Invoke Write-WinUtilHost -Times 0 -Exactly
$content = Get-Content -Path $script:logPath -Raw
$content | Should -Match "\[INFO\] \[UI\] toggle applied"
$content | Should -Match "\[WARN\] \[UI\] toggle warning"
}
It "ignores ordinary output and blank lines" {
Mock Write-WinUtilHost { }
& { "pipeline output"; Write-Host "" } 6>&1 | ForEach-Object {
Write-WinUtilStreamRecord -Record $_ -Component "Tweaks"
}
Test-Path -Path $script:logPath | Should -BeFalse
}
It "moves each record from a runspace that shares the console host into the log once" {
$runspace = [runspacefactory]::CreateRunspace($Host)
$runspace.Open()
$shell = [powershell]::Create()
$shell.Runspace = $runspace
try {
[void]$shell.AddScript({
Write-Host "interface message"
Write-Warning "interface warning"
Write-Error "interface error"
})
$shell.Invoke() | Out-Null
Receive-WinUtilStreamOutput -PowerShell $shell -Component "UI"
Receive-WinUtilStreamOutput -PowerShell $shell -Component "UI"
$shell.Streams.Information.Count | Should -Be 0
$shell.Streams.Warning.Count | Should -Be 0
$shell.Streams.Error.Count | Should -Be 0
} finally {
$shell.Dispose()
$runspace.Dispose()
}
$content = Get-Content -Path $script:logPath
@($content | Where-Object { $_ -match "\[INFO\] \[UI\] interface message$" }).Count | Should -Be 1
@($content | Where-Object { $_ -match "\[WARN\] \[UI\] interface warning$" }).Count | Should -Be 1
@($content | Where-Object { $_ -match "\[ERROR\] \[UI\] Non-terminating error : interface error$" }).Count | Should -Be 1
}
It "keeps console-only helpers out of the information stream" {
# Anything these send through Write-Host would be logged twice inside a job
$failure = try { throw "simulated failure" } catch { $_ }
$records = @(& {
Write-WinUtilLog -Component "Test" -Message "entry"
Write-WinUtilJobBanner -Message "Installing apps"
Write-WinUtilErrorRecord -ErrorRecord $failure -Component "Test"
Write-WinUtilConsoleProgress -Status "Installing" -Percent 10
Complete-WinUtilConsoleProgress
} 6>&1 | Where-Object { $_ -is [System.Management.Automation.InformationRecord] })
$records.Count | Should -Be 0
}
}
Describe "Session log wiring" {
It "does not hand the session log to a transcript" {
# A transcript only records the runspace that starts it, so the UI thread and jobs never
# made it into the file. The ISO post-install script runs on its own and is fine.
$offenders = Get-ChildItem -Path (Join-Path $script:repoRoot "scripts"), (Join-Path $script:repoRoot "functions") -Filter "*.ps1" -Recurse |
Where-Object { $_.Name -ne "Invoke-WinUtilISOScript.ps1" } |
Where-Object { (Get-Content -LiteralPath $_.FullName -Raw) -match "Start-Transcript" } |
ForEach-Object { $_.Name }
$offenders | Should -BeNullOrEmpty
}
It "logs the interface thread's output while the window is open" {
$mainScript = Get-Content -Path (Join-Path $script:repoRoot "scripts\main.ps1") -Raw
$mainScript | Should -Match 'while \(-not \$uiHandle\.AsyncWaitHandle\.WaitOne\(\d+\)\) \{\s*Receive-WinUtilStreamOutput -PowerShell \$uiShell'
$mainScript | Should -Match 'EndInvoke\(\$uiHandle\)[\s\S]*Receive-WinUtilStreamOutput -PowerShell \$uiShell'
}
It "closes the session log on both exits" {
$mainScript = Get-Content -Path (Join-Path $script:repoRoot "scripts\main.ps1") -Raw
([regex]::Matches($mainScript, 'Close-WinUtilLog')).Count | Should -Be 2
}
}
+1
View File
@@ -329,6 +329,7 @@ Describe "Invoke-WinUtilTweaks completion status" {
}
AfterEach {
Close-WinUtilLog
Remove-Variable -Name sync -Scope Script -ErrorAction SilentlyContinue
Remove-Variable -Name WinUtilJobErrorCount -Scope Global -ErrorAction SilentlyContinue
Remove-Item -Path $script:testRoot -Recurse -Force -ErrorAction SilentlyContinue
+2 -1
View File
@@ -437,7 +437,8 @@ Describe "XAML and sync wiring" {
"IsLocalCompile",
"winutildir",
"logPath",
"transcriptPath",
"LogWriter",
"LogWriterPath",
"ActiveJob",
"ActiveJobToken",
"LastJobResult",
+9 -10
View File
@@ -20,6 +20,8 @@ CCC::::::::::::C T:::::::::T T:::::::::T
=====Windows Toolbox=====
"@
Write-WinUtilLog -Message "WinUtil $($sync.version) on PowerShell $($PSVersionTable.PSVersion) ($($PSVersionTable.PSEdition)), $([Environment]::OSVersion.VersionString), process $PID."
# Load the configuration files
$sync.configs.applicationsHashtable = @{}
@@ -95,7 +97,7 @@ if ($Preset -or $Config) {
Close-WinUtilRunspacePool
[System.GC]::Collect()
Remove-WinUtilTempScript
Stop-Transcript | Out-Null
Close-WinUtilLog
}
# An isolated elevated child and an explicit file launch own their process. The documented
@@ -132,7 +134,10 @@ $uiHandle = $uiShell.BeginInvoke()
# leaving it to the thread that is building the window
Start-WinUtilAssetRendering | Out-Null
$uiHandle.AsyncWaitHandle.WaitOne() | Out-Null
# Log the UI thread's Write-Host output, warnings and errors while the window is open
while (-not $uiHandle.AsyncWaitHandle.WaitOne(250)) {
Receive-WinUtilStreamOutput -PowerShell $uiShell -Component "UI"
}
$uiFailed = $false
try {
@@ -142,13 +147,7 @@ try {
Write-WinUtilErrorRecord -ErrorRecord $_ -Component "UI" -Context "Interface thread stopped"
}
foreach ($uiWarning in $uiShell.Streams.Warning) {
Write-WinUtilLog -Level "WARN" -Component "UI" -Message $uiWarning.Message
}
foreach ($uiError in $uiShell.Streams.Error) {
Write-WinUtilErrorRecord -ErrorRecord $uiError -Component "UI" -Context "Interface thread"
}
Receive-WinUtilStreamOutput -PowerShell $uiShell -Component "UI"
$uiShell.Dispose()
$sync.UIRunspace.Dispose()
@@ -163,7 +162,7 @@ Close-WinUtilRunspacePool
Remove-WinUtilTempScript
Write-Host "Bye bye!" -ForegroundColor Cyan
Stop-Transcript
Close-WinUtilLog
if ($uiFailed) {
$global:LASTEXITCODE = 1
+3 -10
View File
@@ -252,16 +252,9 @@ $dateTime = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
$winutildir = "$env:LocalAppData\winutil"
$sync.winutildir = $winutildir
$logdir = "$winutildir\logs"
# Start-Transcript fails outright when the directory is missing, which is every first run
if (-not (Test-Path $logdir)) {
New-Item -ItemType Directory -Path $logdir -Force | Out-Null
}
# Keep console output and structured entries in the path reported to the user. Write-WinUtilLog
# writes through the host while this transcript owns the file, avoiding competing file handles.
$sync.logPath = "$logdir\winutil_$dateTime.log"
$sync.transcriptPath = $sync.logPath
Start-Transcript -Path $sync.transcriptPath -Append -NoClobber | Out-Null
# Written by Write-WinUtilLog. Not a transcript, as that only records this runspace and misses
# everything from the UI thread and the jobs.
$sync.logPath = "$winutildir\logs\winutil_$dateTime.log"
$Host.UI.RawUI.WindowTitle = "WinUtil"
Clear-Host