Collect what bays actually have, separately from what they are told to have
Some checks failed
CI / backend (push) Failing after 7m15s
CI / naming (push) Failing after 7m22s
CI / frontend (push) Failing after 7m14s
CI / migrations-mysql (push) Failing after 7m14s

ShopDB knew what a bay SHOULD have and nothing about what it DOES. Adding the
observed half makes a rollout a review instead of a typing exercise: the floor
reports itself in, you look, and you adopt.

The collection uses the mechanism that already exists rather than a new one.
POST /api/collector/printers dispatches to the printers plugin's
apply_collector_payload, the same ADR-006 hook the computers and backups plugins
implement. New client script, new plugin-owned table, no new transport and no new
credential.

OBSERVED AND ASSIGNED STAY APART, and that is the point rather than a detail. A
collector report can never write an assignment row: _reconcile_edges is the only
function that writes usesprinter/defaultprinter, it has two call sites, and both
are authenticated routes a human calls. If a drifted bay's own state were allowed
to become what it is told to install, every configuration error would become
permanent the next time that PC checked in.

Seeding an assignment from observed state is explicit -
POST /assignments/seed-from-observed - because a rollout adopts many machines at
once. It routes through the same _reconcile_edges as the editor, so there is one
write path with two doors, and a queue matching no known printer is REFUSED
rather than guessed into an assignment. That last rule is the lesson from the
measuring tools: adopting on a weak key produced 43 duplicate instruments.

Two fixes on top of what the agents built. The replace deleted a host's previous
rows by exact case-folded name while the read path treats a short name and its
FQDN as one machine, so a PC that changed spelling appeared to hold every queue
twice - which reads as drift that is not there. And the client sent 'reportedat'
where the declared schema said 'observedat'.

Also here: the legacy loader now imports machines.printerid, the classic system's
record of each machine's default printer, which it silently dropped - the
production import would have lost every one. And Set-ShopdbPrinters.ps1 finally
registers the per-user logon task, staging Apply-ShopdbDefaultPrinter.ps1 to
C:\ProgramData first because the share it lives on is mounted only during the
enforcement cycle and the task runs at logon when it is gone.

VALIDATED ON WINDOWS 11 (build 26200), not just on Linux pwsh, which parses these
scripts happily and executes none of the spooler branches.

The reporter: posts a correct payload with the X-API-Key header; resolves BaseUrl
and CollectorKey from HKLM when given no arguments; suppresses the virtual queues
by port; resolves port addresses; and reads the CONSOLE USER's default out of
HKU rather than SYSTEM's own, which is a different and usually wrong answer.

Two results matter more than the rest. With the spooler stopped, both the cmdlet
and the CIM path fail and the script posts NOTHING - verified against a capture
server that recorded zero requests, where an empty list would instead have
erased that host's observed rows and read as a bay that lost its printers. A
genuinely empty host still posts [], because that is a real and different fact.

The logon task registers as the Users group at Limited, and falls back to the
well-known SID S-1-5-32-545 when the group name will not resolve, as it will not
on localised Windows. It was then run with the source directory RENAMED AWAY, to
stand in for the share being unmounted, and it still moved the user's default -
which is the whole reason the script is staged to C:\ProgramData rather than run
from where it lives.

The guarantees against damage were re-checked rather than assumed: an empty
assignment changes nothing, an unreachable server changes nothing, -WhatIfOnly
leaves no queue, no task, no staged file and no registry value behind, and a
drifted queue is repointed IN PLACE with Set-Printer so whoever has it as their
default keeps it.

Not covered by any of this: the driver-staging path, which needs a real vendor
package rather than the class drivers a VM ships with.
This commit is contained in:
cproudlock
2026-08-19 14:45:39 -04:00
parent 1a5a1cd43d
commit 2d09fa3201
15 changed files with 2903 additions and 30 deletions

View File

@@ -0,0 +1,314 @@
# Report-PrintersToShopDB.ps1
#
# Reports the print queues this PC ACTUALLY has to ShopDB, so the register can
# be compared against what the bay is SUPPOSED to have. ShopDB knows the
# assignment (GET /api/printers/for-host/<hostname>, applied by
# Set-ShopdbPrinters.ps1); it has never known what is really installed. This is
# that missing half.
#
# TARGET: the ADR-006 collector API.
# POST <shopdb>/api/collector/printers
# The server is NOT baked in. It comes from HKLM:\SOFTWARE\GE\ShopDB BaseUrl,
# which Install-GEEnforce.ps1 provisions and the enforcement client already
# needs, or from -ApiUrl in the manifest entry's Args. ADR-015: a site name in
# product code is a defect, and this script ships to every site.
#
# READ ONLY. It calls nothing that creates, changes or removes a queue, a port
# or a driver - only Get-*. Convergence is Set-ShopdbPrinters.ps1's job and
# stays there; a reporter that also fixes things cannot be trusted to tell you
# what was broken.
#
# OBSERVED IS NOT ASSIGNED. The server stores this in its own table and never
# turns it into an assignment on its own. A drifted bay reporting its drift must
# not be able to redefine what correct means.
#
# THE LATEST REPORT REPLACES THE PREVIOUS ONE for this hostname, which makes an
# empty queues list a legitimate "this bay has no printers" and wipes the host's
# observed rows. So a FAILED enumeration must send NOTHING rather than an empty
# list - see the $enumerated flag below. Reporting nothing loses one cycle;
# reporting [] after a WMI hiccup deletes real state and reads as a bay that
# lost its printers.
#
# AUTH: the collector API does NOT honor the GE-Enforce IP allowlist (that only
# covers the geenforce fetch/report endpoints). It needs a collector.ingest key,
# sent as the X-API-Key header. The key is read from HKLM:\SOFTWARE\GE\ShopDB
# CollectorKey (the same secret store Report-AssetToShopDB.ps1 uses; provisioned
# at imaging), or overridden via the manifest entry's Args -ApiKey. Never bake
# the key into the manifest JSON on the share.
#
# Runs every GE-Enforce cycle as a Type=PS1 / DetectionMethod=Always entry under
# the SYSTEM task. Always exits 0 so a printer problem never fails an
# enforcement run; failures are logged, never thrown.
param(
# Flask collector endpoint for the printers plugin. Empty resolves from
# HKLM:\SOFTWARE\GE\ShopDB BaseUrl; override here if the path ever moves.
[string]$ApiUrl = '',
# collector.ingest key (X-API-Key). Default: read from the GE-Enforce secret
# store in the registry. Override with -ApiKey via Args for testing.
[string]$ApiKey = '',
# Identity field of the payload. Defaults to this machine's name, which is
# what the assignment side (for-host) and the computers collector both key on.
[string]$Hostname = $env:COMPUTERNAME,
[int]$TimeoutSec = 30,
# Enumerate and log the payload, post nothing. For proving what a bay would
# report before a site is pointed at a live server.
[switch]$WhatIfOnly
)
$ErrorActionPreference = 'Continue'
# Force TLS 1.2 - older images default to SystemDefault which may negotiate a
# protocol the site rejects; the collector POST is HTTPS.
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$logDir = 'C:\Logs\Shopfloor'
if (-not (Test-Path $logDir)) {
New-Item -ItemType Directory -Path $logDir -Force -ErrorAction SilentlyContinue | Out-Null
}
$logFile = Join-Path $logDir ('report-printers-{0}.log' -f (Get-Date -Format 'yyyyMMdd'))
function Log([string]$msg) {
$ts = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
"$ts $msg" | Tee-Object -FilePath $logFile -Append | Out-Null
}
$REGPATHS = @('HKLM:\SOFTWARE\GE\ShopDB', 'HKLM:\SOFTWARE\WOW6432Node\GE\ShopDB')
function Get-ShopdbRegValue([string]$name) {
foreach ($path in $REGPATHS) {
try {
if (Test-Path $path) {
$value = [string](Get-ItemProperty -Path $path -Name $name -ErrorAction Stop).$name
if ($value -and $value.Trim()) { return $value.Trim() }
}
} catch {}
}
return ''
}
Log "=== Report printers to ShopDB (collector) : $Hostname ==="
# Server from the GE-Enforce config hive when not passed via Args. Any site
# running this script is running the enforcement client, which cannot work
# without BaseUrl, so it is present wherever this is deployed.
if (-not $ApiUrl) {
$base = Get-ShopdbRegValue 'BaseUrl'
if ($base) { $ApiUrl = $base.TrimEnd('/') + '/api/collector/printers' }
}
if (-not $ApiUrl -and -not $WhatIfOnly) {
Log 'ERROR no ShopDB URL (HKLM:\SOFTWARE\GE\ShopDB BaseUrl or -ApiUrl). Skipping.'
exit 0
}
# collector key from the GE-Enforce secret store when not passed via Args.
if (-not $ApiKey) { $ApiKey = Get-ShopdbRegValue 'CollectorKey' }
if (-not $ApiKey -and -not $WhatIfOnly) {
Log 'ERROR no collector key (HKLM:\SOFTWARE\GE\ShopDB CollectorKey or -ApiKey). Skipping.'
exit 0
}
# Queues that are not devices: the Windows-supplied virtual printers plus the
# Office writers. They exist on every image, match nothing in the register, and
# would each land as an UNKNOWN row on every bay in the fleet.
#
# Matched on the PORT, not the queue name, because the name is whatever a user
# renamed it to while the port of a virtual device is fixed. Two of them are
# matched on driver as well, since a redirected-port queue can share PORTPROMPT.
$VIRTUALPORTS = @('PORTPROMPT:', 'SHRFAX:', 'XPSPort:', 'nul:', 'NUL:')
$VIRTUALDRIVERS = @(
'Microsoft XPS Document Writer',
'Microsoft XPS Document Writer v4',
'Microsoft Print To PDF',
'Microsoft Shared Fax Driver',
'Send to Microsoft OneNote Driver',
'Microsoft Software Printer Driver'
)
function Test-VirtualQueue([string]$portname, [string]$drivername) {
foreach ($p in $VIRTUALPORTS) {
if ($portname -and $portname.Trim().ToLower() -eq $p.ToLower()) { return $true }
}
# OneNote's port is a per-install GUID path, so it can only be caught here.
if ($portname -and $portname -like 'Microsoft.Office.OneNote*') { return $true }
foreach ($d in $VIRTUALDRIVERS) {
if ($drivername -and $drivername.Trim().ToLower() -eq $d.ToLower()) { return $true }
}
return $false
}
# Port address is the primary match key server-side: an IP or FQDN is
# unambiguous where a queue name is a local habit. Built once as a lookup so a
# bay with 8 queues does not re-enumerate ports 8 times.
#
# A port with no host address (USB, WSD, a redirected port) reports a null
# address and matches on name alone, which is correct: a locally attached
# printer is still a real printer worth seeing.
$portAddresses = @{}
$portsRead = $false
try {
foreach ($port in (Get-PrinterPort -ErrorAction Stop)) {
$address = ''
if ($port.PSObject.Properties['PrinterHostAddress']) {
$address = [string]$port.PrinterHostAddress
}
if ($port.Name) { $portAddresses[[string]$port.Name] = $address.Trim() }
}
$portsRead = $true
} catch {
Log "WARN Get-PrinterPort failed, falling back to WMI ports: $($_.Exception.Message)"
}
if (-not $portsRead) {
# PS 5.1-era hosts without the PrintManagement module, and images where the
# spooler cmdlets are broken but WMI still answers.
try {
foreach ($port in (Get-CimInstance -ClassName Win32_TCPIPPrinterPort -ErrorAction Stop)) {
if ($port.Name) { $portAddresses[[string]$port.Name] = ([string]$port.HostAddress).Trim() }
}
$portsRead = $true
} catch {
# Not fatal: queues still report, just without an address to match on.
Log "WARN could not read printer ports at all: $($_.Exception.Message)"
}
}
# The queues themselves. $enumerated stays false unless a read actually
# succeeded, because "no queues" and "could not look" are the same empty list
# and the server treats them very differently (see the header).
$queues = @()
$enumerated = $false
try {
foreach ($printer in (Get-Printer -ErrorAction Stop)) {
$queues += [pscustomobject]@{
queuename = [string]$printer.Name
drivername = [string]$printer.DriverName
portname = [string]$printer.PortName
}
}
$enumerated = $true
} catch {
Log "WARN Get-Printer failed, falling back to WMI queues: $($_.Exception.Message)"
}
if (-not $enumerated) {
try {
foreach ($printer in (Get-CimInstance -ClassName Win32_Printer -ErrorAction Stop)) {
$queues += [pscustomobject]@{
queuename = [string]$printer.Name
drivername = [string]$printer.DriverName
portname = [string]$printer.PortName
}
}
$enumerated = $true
} catch {
Log "ERROR could not enumerate printers: $($_.Exception.Message)"
}
}
if (-not $enumerated) {
# Deliberately posts nothing. An empty report REPLACES this host's observed
# rows, so a failed read must not be able to claim the bay has no printers.
Log 'ERROR enumeration failed; posting NOTHING so the last good report stands.'
exit 0
}
# Which queue the interactive user actually prints to. This process is SYSTEM,
# and the default printer is per user, so Win32_Printer.Default here describes
# the SYSTEM session and is usually wrong. Read the console user's own value
# first: HKU\<sid>\...\Windows Device holds "<queue>,winspool,<port>".
$defaultName = ''
try {
$consoleUser = [string](Get-CimInstance -ClassName Win32_ComputerSystem -ErrorAction Stop).UserName
if ($consoleUser) {
$sid = (New-Object System.Security.Principal.NTAccount($consoleUser)).Translate(
[System.Security.Principal.SecurityIdentifier]).Value
$devicePath = "Registry::HKEY_USERS\$sid\Software\Microsoft\Windows NT\CurrentVersion\Windows"
$device = [string](Get-ItemProperty -Path $devicePath -Name Device -ErrorAction Stop).Device
if ($device) { $defaultName = ($device -split ',')[0].Trim() }
if ($defaultName) { Log "default for $consoleUser : $defaultName" }
}
} catch {
# Nobody logged on, a roaming hive not loaded, or a name that will not
# translate. Not worth a warning every cycle on an unattended bay.
}
if (-not $defaultName) {
# Falls back to whatever this session sees. Marked in the log because a
# SYSTEM-session default is weak evidence and a reviewer should know which
# one they are looking at before seeding an assignment from it.
try {
$sysDefault = Get-CimInstance -ClassName Win32_Printer -ErrorAction Stop |
Where-Object { $_.Default } | Select-Object -First 1
if ($sysDefault) {
$defaultName = [string]$sysDefault.Name
Log "default from the SYSTEM session (no console user): $defaultName"
}
} catch {}
}
$reported = @()
$skipped = 0
foreach ($queue in $queues) {
if (-not $queue.queuename) { continue }
if (Test-VirtualQueue $queue.portname $queue.drivername) { $skipped++; continue }
$portAddress = ''
if ($queue.portname -and $portAddresses.ContainsKey($queue.portname)) {
$portAddress = [string]$portAddresses[$queue.portname]
}
$row = @{
queuename = $queue.queuename
isdefault = ($defaultName -and $queue.queuename -eq $defaultName)
}
# Sent only when present: a null is "not known", and an empty string would
# read as a driver or a port genuinely named nothing.
if ($queue.drivername) { $row['drivername'] = $queue.drivername }
if ($queue.portname) { $row['portname'] = $queue.portname }
if ($portAddress) { $row['portaddress'] = $portAddress }
$reported += $row
Log ("queue: {0} | driver={1} | port={2} | address={3} | default={4}" -f `
$queue.queuename, $queue.drivername, $queue.portname, $portAddress, $row['isdefault'])
}
Log "reporting $($reported.Count) queue(s), $skipped virtual queue(s) skipped"
if ($reported.Count -eq 0) {
# Legitimate and meaningful: it clears this host's observed rows so the
# comparison shows every assigned printer as missing, which is exactly what
# a bay with no queues is.
Log 'no real queues on this host; reporting an empty set (clears observed state)'
}
# Collector schema fields (lowercase concatenated). hostname is the identity
# field. observedat is sent for the record and named to match the declared
# collector schema; the server stamps its own and ignores this one.
$body = @{
hostname = $Hostname
queues = @($reported)
observedat = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss')
}
# Depth 4 covers hostname -> queues -> row -> value; the default of 2 flattens
# the rows to type names.
$json = $body | ConvertTo-Json -Compress -Depth 4
if ($WhatIfOnly) {
Log "WOULD POST $ApiUrl $json"
exit 0
}
Log ("POST {0} host={1} queues={2}" -f $ApiUrl, $Hostname, $reported.Count)
try {
$response = Invoke-RestMethod -Uri $ApiUrl -Method Post -Body $json `
-ContentType 'application/json' `
-Headers @{ 'X-API-Key' = $ApiKey } `
-TimeoutSec $TimeoutSec -ErrorAction Stop
Log ("RESPONSE {0}" -f ($response | ConvertTo-Json -Compress -Depth 4))
} catch {
Log "ERROR POST failed: $($_.Exception.Message)"
}
exit 0

View File

@@ -24,6 +24,12 @@
# logged-on person, so it records the desired default in HKLM and leaves applying
# it to a logon task. Without that, SYSTEM would set a default nobody sees.
#
# IT ALSO REGISTERS THAT LOGON TASK, and stages a LOCAL copy of
# Apply-ShopdbDefaultPrinter.ps1 for it to run. Recording a default that nothing
# ever applies was the gap: the queues appeared, the default never moved. The
# local copy is not tidiness - the share this script runs from is mounted only
# for the enforcement cycle, and the task fires at logon when it is gone.
#
# Exits 0 always: a printer problem must not fail an enforcement run.
param(
@@ -36,6 +42,26 @@ param(
[int]$TimeoutSec = 30,
# Where the per-user logon script is staged. Anywhere is fine as long as it
# is on this PC and every user can read it.
[string]$LocalScriptDir = (Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'ShopDB'),
[string]$LogonTaskName = 'ShopDB default printer',
# The task runs as a GROUP, not a person: a shared bay has no one owner and
# the default must be applied for whoever logs on. If this name does not
# resolve - it is localised on non-English Windows - the well-known SID is
# tried instead.
[string]$UsersGroup = 'BUILTIN\Users',
# 0 means at logon only. A shared bay where people pick their own default
# can be pulled back on a repeat; a single-user PC should not be, so the
# neutral default is the one that does not argue with the user.
[int]$RepeatMinutes = 0,
# For a site that deploys the logon task by GPO instead.
[switch]$NoLogonTask,
# Report what would change and touch nothing.
[switch]$WhatIfOnly
)
@@ -53,6 +79,127 @@ function Log([string]$msg) {
"$ts $msg" | Tee-Object -FilePath $logFile -Append | Out-Null
}
# Resolved once, at script scope: $PSScriptRoot is empty when the file is piped
# into powershell rather than run by path, and the logon script sits beside this
# one.
$SCRIPTDIR = $PSScriptRoot
if (-not $SCRIPTDIR -and $MyInvocation.MyCommand.Path) {
$SCRIPTDIR = Split-Path -Parent $MyInvocation.MyCommand.Path
}
function Ensure-LogonTask {
# Half of this feature is per-user state that SYSTEM cannot write. All SYSTEM
# can do is arrange for something to run AS the user later, which is this
# task. Nothing else registered it, so the default was recorded every cycle
# and applied never.
if ($NoLogonTask) {
Log 'logon task: skipped (-NoLogonTask)'
return
}
$source = ''
if ($SCRIPTDIR) { $source = Join-Path $SCRIPTDIR 'Apply-ShopdbDefaultPrinter.ps1' }
if (-not $source -or -not (Test-Path $source)) {
Log "SKIP logon task: Apply-ShopdbDefaultPrinter.ps1 is not beside this script"
return
}
# THE LOCAL COPY IS LOAD-BEARING. This script runs from a share that is
# mounted only for the enforcement cycle; the task fires at logon, when the
# share is gone. A task pointing at the share never runs and says nothing.
$localscript = Join-Path $LocalScriptDir 'Apply-ShopdbDefaultPrinter.ps1'
$refreshed = $false
try {
if (-not (Test-Path $LocalScriptDir)) {
# Inherited ACL is what is wanted here: every user can read it, only
# admins can write it, so the task cannot be pointed somewhere else.
New-Item -ItemType Directory -Path $LocalScriptDir -Force -ErrorAction Stop | Out-Null
}
$stale = $true
if (Test-Path $localscript) {
$stale = (Get-FileHash -Path $localscript -Algorithm SHA256).Hash -ne
(Get-FileHash -Path $source -Algorithm SHA256).Hash
}
if ($stale) {
if ($WhatIfOnly) {
Log "WOULD stage the logon script at $localscript"
} else {
Copy-Item -Path $source -Destination $localscript -Force -ErrorAction Stop
$refreshed = $true
Log "staged the logon script at $localscript"
}
}
} catch {
# No local copy means no task worth registering - a task pointing at a
# file that is not there is worse than no task, because it looks fine.
Log "ERROR staging ${localscript}: $($_.Exception.Message)"
return
}
$arguments = "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$localscript`""
$task = Get-ScheduledTask -TaskName $LogonTaskName -ErrorAction SilentlyContinue
if ($task -and -not $refreshed) {
# Re-registering every cycle throws away the task's run history, which
# is the only evidence it ever fired. So it is replaced only when it
# points somewhere other than the local copy, or has no group principal
# - a task left behind running as one person applies one person's
# default. Matched on the PATH rather than the whole argument string
# because Task Scheduler is free to normalise quoting, and an exact
# compare would churn over a difference that changes nothing.
$registered = @($task.Actions)[0]
$pointslocal = $registered -and $registered.Arguments -and
$registered.Arguments.IndexOf($localscript, [StringComparison]::OrdinalIgnoreCase) -ge 0
if ($pointslocal -and $task.Principal.GroupId) {
Log "logon task present: $LogonTaskName"
return
}
}
if ($WhatIfOnly) {
Log "WOULD register the logon task: $LogonTaskName -> $localscript"
return
}
try {
$triggers = @(New-ScheduledTaskTrigger -AtLogOn)
if ($RepeatMinutes -gt 0) {
$triggers += New-ScheduledTaskTrigger -Once -At (Get-Date) `
-RepetitionInterval (New-TimeSpan -Minutes $RepeatMinutes)
}
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument $arguments
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries `
-DontStopIfGoingOnBatteries -StartWhenAvailable
} catch {
# An SKU without the ScheduledTasks module is the likely reason. Nothing
# to register with, and still not a reason to fail the run.
Log "ERROR building the logon task: $($_.Exception.Message)"
return
}
# Limited, not Highest: setting your own default printer needs no elevation,
# and a task the whole Users group can trigger should not have any.
$candidates = @($UsersGroup)
if ($UsersGroup -ne 'S-1-5-32-545') { $candidates += 'S-1-5-32-545' }
$lasterror = 'no principal accepted'
foreach ($groupid in $candidates) {
try {
$principal = New-ScheduledTaskPrincipal -GroupId $groupid -RunLevel Limited -ErrorAction Stop
Register-ScheduledTask -TaskName $LogonTaskName -Action $action -Trigger $triggers `
-Principal $principal -Settings $settings -Force -ErrorAction Stop | Out-Null
Log "registered the logon task: $LogonTaskName as $groupid"
return
} catch {
$lasterror = $_.Exception.Message
}
}
# A missing logon task means the default is not applied. It does not mean the
# queues are wrong, so it is logged and the run carries on.
Log "ERROR registering ${LogonTaskName}: $lasterror"
}
$REGPATH = 'HKLM:\SOFTWARE\GE\ShopDB'
if (-not $BaseUrl) {
@@ -72,6 +219,11 @@ if (-not $BaseUrl) {
Log "=== Set printers for $Hostname ==="
# Before the API call on purpose: the task depends on files on this PC, not on
# the server. A bad minute from the API must not leave a bay with no way to apply
# the default it was already told about.
Ensure-LogonTask
$url = $BaseUrl.TrimEnd('/') + '/api/printers/for-host/' + [uri]::EscapeDataString($Hostname)
try {
$response = Invoke-RestMethod -Uri $url -Method Get -TimeoutSec $TimeoutSec
@@ -206,7 +358,8 @@ foreach ($printer in $wanted) {
}
# The default is recorded, not applied: this process is SYSTEM and the setting
# is per user. Apply-ShopdbDefaultPrinter.ps1 reads it at logon.
# is per user. The logon task registered above runs
# Apply-ShopdbDefaultPrinter.ps1, which reads this value in the user's context.
if ($defaultname) {
if ($WhatIfOnly) {
Log "WOULD record default: $defaultname"