Printer assignment end to end, and a container that keeps a site's files
Assign printers to a MACHINE and let whichever PC controls it install them, with the observed half kept strictly apart from the assigned half: a collector report can never write an assignment row. Adoption is explicit. Adds a singular relationship type so defaultprinter can mean exactly one, client scripts that converge a bay's queues and correct a drifted one in place, and a wave gate so a fleet-wide driver rollout cannot stampede its own share. On the container side: the compose stack never persisted the instance directory, so a rebuild discarded plugins.json and every upload. It is a volume now, the image ships instance/ owned by the app user so the mountpoint is writable, and the database moves to MySQL 8.4 LTS, which the Windows runbook has recommended since 8.0 went end of life. The image also could not build at all: the frontend stage never copied the plugin staging script it runs. Adds a topology migration guide covering IIS to Docker and back.
This commit is contained in:
94
plugins/printers/client/Apply-ShopdbDefaultPrinter.ps1
Normal file
94
plugins/printers/client/Apply-ShopdbDefaultPrinter.ps1
Normal file
@@ -0,0 +1,94 @@
|
||||
# Apply-ShopdbDefaultPrinter.ps1
|
||||
#
|
||||
# Sets the logged-on user's default printer to the one ShopDB assigned. Runs IN
|
||||
# THE USER'S CONTEXT, at logon and on a repeat, because a default printer is
|
||||
# per-user state that SYSTEM cannot set for somebody else.
|
||||
#
|
||||
# Set-ShopdbPrinters.ps1 records the desired queue in
|
||||
# HKLM:\SOFTWARE\GE\ShopDB DefaultPrinter during the enforcement cycle. This
|
||||
# reads it. Splitting the two is not tidiness: the machine half needs SYSTEM and
|
||||
# the share, the user half needs a user - no single process has both.
|
||||
#
|
||||
# IT ALSO TURNS OFF "Let Windows manage my default printer". Leaving it on means
|
||||
# Windows silently overwrites the choice the next time somebody prints to another
|
||||
# queue, and the bay drifts back with nothing in any log to say why.
|
||||
#
|
||||
# Converges: when the current default already matches, it does nothing, so a
|
||||
# repeating trigger costs a registry read. A user who deliberately picks another
|
||||
# default WILL be corrected on the next run - that is the intent for a shared
|
||||
# bay. For a PC where that is wrong, schedule it at logon only.
|
||||
#
|
||||
# Exits 0 always.
|
||||
|
||||
param(
|
||||
# Override for testing. Normally read from the machine hive.
|
||||
[string]$PrinterName = ''
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Continue'
|
||||
|
||||
$logDir = "$env:LOCALAPPDATA\ShopDB"
|
||||
if (-not (Test-Path $logDir)) {
|
||||
New-Item -ItemType Directory -Path $logDir -Force -ErrorAction SilentlyContinue | Out-Null
|
||||
}
|
||||
$logFile = Join-Path $logDir 'default-printer.log'
|
||||
function Log([string]$msg) {
|
||||
$ts = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
|
||||
"$ts $msg" | Tee-Object -FilePath $logFile -Append | Out-Null
|
||||
}
|
||||
|
||||
if (-not $PrinterName) {
|
||||
foreach ($path in @('HKLM:\SOFTWARE\GE\ShopDB', 'HKLM:\SOFTWARE\WOW6432Node\GE\ShopDB')) {
|
||||
try {
|
||||
if (Test-Path $path) {
|
||||
$value = [string](Get-ItemProperty -Path $path -Name DefaultPrinter -ErrorAction Stop).DefaultPrinter
|
||||
if ($value -and $value.Trim()) { $PrinterName = $value.Trim(); break }
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $PrinterName) {
|
||||
# No default assigned is a legitimate state - a bay with three printers and
|
||||
# no favourite - so leave whatever the user has.
|
||||
Log 'no default assigned in ShopDB; leaving the current one alone'
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Windows 10+ overrides any default the moment the user prints elsewhere, unless
|
||||
# this is off. Setting the default without clearing this is a fix that undoes
|
||||
# itself within a day.
|
||||
try {
|
||||
$windowsKey = 'HKCU:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows'
|
||||
$managed = (Get-ItemProperty -Path $windowsKey -Name LegacyDefaultPrinterMode -ErrorAction SilentlyContinue).LegacyDefaultPrinterMode
|
||||
if ($managed -ne 1) {
|
||||
Set-ItemProperty -Path $windowsKey -Name LegacyDefaultPrinterMode -Value 1 -Type DWord
|
||||
Log 'turned off "Let Windows manage my default printer"'
|
||||
}
|
||||
} catch {
|
||||
Log "WARN could not turn off Windows-managed defaults: $($_.Exception.Message)"
|
||||
}
|
||||
|
||||
$queue = Get-Printer -Name $PrinterName -ErrorAction SilentlyContinue
|
||||
if (-not $queue) {
|
||||
# The enforcement cycle creates queues; this runs at logon and may simply be
|
||||
# earlier than the first cycle on a new bay. Next run picks it up.
|
||||
Log "assigned default '$PrinterName' is not installed yet; nothing to do"
|
||||
exit 0
|
||||
}
|
||||
|
||||
$current = (Get-CimInstance -ClassName Win32_Printer -Filter 'Default = True' -ErrorAction SilentlyContinue).Name
|
||||
if ($current -eq $PrinterName) {
|
||||
Log "already default: $PrinterName"
|
||||
exit 0
|
||||
}
|
||||
|
||||
try {
|
||||
$target = Get-CimInstance -ClassName Win32_Printer -Filter ("Name = '{0}'" -f $PrinterName.Replace("'", "''")) -ErrorAction Stop
|
||||
Invoke-CimMethod -InputObject $target -MethodName SetDefaultPrinter -ErrorAction Stop | Out-Null
|
||||
Log "default set: $PrinterName (was '$current')"
|
||||
} catch {
|
||||
Log "ERROR setting the default to '$PrinterName': $($_.Exception.Message)"
|
||||
}
|
||||
|
||||
exit 0
|
||||
144
plugins/printers/client/DEPLOYING-DRIVERS.md
Normal file
144
plugins/printers/client/DEPLOYING-DRIVERS.md
Normal file
@@ -0,0 +1,144 @@
|
||||
# Deploying the printer driver set
|
||||
|
||||
The driver set is a package: `Install-ShopdbPrinterDrivers.ps1`, the
|
||||
single-driver worker it wraps, a `drivers.json` naming each driver and where its
|
||||
files are, and the driver packages themselves.
|
||||
|
||||
Staging drivers is deliberately SEPARATE from assigning printers. Drivers are
|
||||
large, change rarely and are identical across a fleet; assignments are small,
|
||||
per-bay and change often. Keeping them apart means creating a queue never waits
|
||||
on a download, and a driver never has to be fetched at the moment someone is
|
||||
trying to print.
|
||||
|
||||
## The shape
|
||||
|
||||
```
|
||||
ShopdbPrinterDrivers\
|
||||
Install-ShopdbPrinterDrivers.ps1 the whole set, manifest driven
|
||||
Install-ShopdbPrinterDriver.ps1 one driver (this does the work)
|
||||
drivers.json what this site deploys
|
||||
drivers\
|
||||
hp_upd_ps\ xerox_gpd\ hp_designjet\ zebra_zt411\ ...
|
||||
```
|
||||
|
||||
`drivers.json` paths may be relative to the package or absolute. A site whose
|
||||
packages already live on a share points at the share and ships only the two
|
||||
scripts and the manifest.
|
||||
|
||||
## GE-Enforce, in the `common` scope
|
||||
|
||||
Every shop-floor PC gets every driver, once. After the first cycle each run is a
|
||||
`Get-PrinterDriver` check per driver and nothing else, so the cost is a few
|
||||
milliseconds, not a re-install.
|
||||
|
||||
```json
|
||||
{
|
||||
"_comment": "Stage the site's printer drivers. Runs in-cycle because the share is only mounted then. Idempotent: a driver already present is skipped.",
|
||||
"Name": "ShopDB printer drivers",
|
||||
"Type": "PS1",
|
||||
"Script": "scripts/Install-ShopdbPrinterDrivers.ps1",
|
||||
"DetectionMethod": "Always"
|
||||
}
|
||||
```
|
||||
|
||||
**It must be a manifest entry, not its own scheduled task.** The SFLD share is
|
||||
mounted only for the duration of the enforcement cycle; off-cycle the paths
|
||||
simply do not exist and every run logs "package not found" forever.
|
||||
|
||||
## Azure Machine Configuration / DSC
|
||||
|
||||
The script answers a compliance question, which is what makes it a clean `Script`
|
||||
resource: `-TestOnly` reports whether every driver in the manifest is present and
|
||||
exits 0 or 1 without changing anything.
|
||||
|
||||
```powershell
|
||||
Configuration ShopdbPrinterDrivers
|
||||
{
|
||||
Import-DscResource -ModuleName PSDesiredStateConfiguration
|
||||
|
||||
Node localhost
|
||||
{
|
||||
Script PrinterDrivers
|
||||
{
|
||||
GetScript = {
|
||||
@{ Result = (Get-PrinterDriver | Select-Object -ExpandProperty Name) -join ', ' }
|
||||
}
|
||||
TestScript = {
|
||||
$p = Start-Process -FilePath 'powershell.exe' -PassThru -Wait -WindowStyle Hidden `
|
||||
-ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-File',
|
||||
'C:\ProgramData\ShopDB\Drivers\Install-ShopdbPrinterDrivers.ps1','-TestOnly'
|
||||
return ($p.ExitCode -eq 0)
|
||||
}
|
||||
SetScript = {
|
||||
Start-Process -FilePath 'powershell.exe' -Wait -WindowStyle Hidden `
|
||||
-ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-File',
|
||||
'C:\ProgramData\ShopDB\Drivers\Install-ShopdbPrinterDrivers.ps1'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Deliver the package to `C:\ProgramData\ShopDB\Drivers` however that estate
|
||||
already delivers files - a Win32 app, a File resource, or the imaging step.
|
||||
|
||||
## Intune
|
||||
|
||||
Package the folder as a Win32 app.
|
||||
|
||||
- Install: `powershell.exe -NoProfile -ExecutionPolicy Bypass -File Install-ShopdbPrinterDrivers.ps1`
|
||||
- Detection: a script running the same file with `-TestOnly`, exit 0 = detected
|
||||
- Run as SYSTEM. Adding a printer driver has required administrator rights since
|
||||
the 2021 print hardening, and SYSTEM satisfies it.
|
||||
|
||||
## Why not have the assignment client fetch drivers
|
||||
|
||||
It was considered and rejected. A bay would then download a driver at the moment
|
||||
a printer is assigned, which is the worst time: someone is waiting, the share may
|
||||
be unmounted, and a 48 MB package would be pulled per bay per change. Staging the
|
||||
set in `common` makes assignment a queue creation and nothing more.
|
||||
|
||||
## One driver per package, named exactly
|
||||
|
||||
`drivers.json` carries the driver name as its INF declares it - `Add-PrinterDriver`
|
||||
matches that string and nothing else. The names verified on Windows for the
|
||||
reference site's fleet:
|
||||
|
||||
| driver | covers |
|
||||
|---|---|
|
||||
| `HP Universal Printing PS` | HP office printers |
|
||||
| `Xerox Global Print Driver PCL6` | Xerox office printers |
|
||||
| `HP DesignJet T1700dr V4` | DesignJet plotters (a v4 class driver) |
|
||||
| `ZDesigner ZT411-300dpi ZPL` | Zebra ZT411 labels |
|
||||
| `EPSON TM-C3500` | Epson ColorWorks labels |
|
||||
| `DTC4500e Card Printer` | HID FARGO card printer |
|
||||
|
||||
## The other half: assigning printers
|
||||
|
||||
Staging drivers is only delivery. `Set-ShopdbPrinters.ps1` is what makes a bay's
|
||||
queues match ShopDB, and `Apply-ShopdbDefaultPrinter.ps1` applies the default in
|
||||
the user's context. Two manifest entries, both `DetectionMethod: Always`:
|
||||
|
||||
```json
|
||||
{
|
||||
"_comment": "Create the queues this bay is assigned. Converges: existing queues are left alone, and nothing is ever removed.",
|
||||
"Name": "ShopDB printers",
|
||||
"Type": "PS1",
|
||||
"Script": "scripts/Set-ShopdbPrinters.ps1",
|
||||
"DetectionMethod": "Always"
|
||||
}
|
||||
```
|
||||
|
||||
The default printer is per-user, so SYSTEM cannot set it for the person logged
|
||||
on. `Set-ShopdbPrinters.ps1` records it in `HKLM:\SOFTWARE\GE\ShopDB`
|
||||
`DefaultPrinter`, and `Apply-ShopdbDefaultPrinter.ps1` runs as the user - at
|
||||
logon, and on a repeat if the site wants drift corrected.
|
||||
|
||||
Order matters on a new bay: drivers, then queues, then the default. Each step is
|
||||
a no-op once satisfied, so running all three every cycle costs a few registry
|
||||
reads.
|
||||
|
||||
Verified end to end on Windows 11 against a live ShopDB: printers assigned to a
|
||||
MACHINE, a PC controlling it and holding no rows of its own, and the bay created
|
||||
both queues with the right universal driver, recorded the default, and set it -
|
||||
then a second run changed nothing.
|
||||
193
plugins/printers/client/Install-ShopdbPrinterDriver.ps1
Normal file
193
plugins/printers/client/Install-ShopdbPrinterDriver.ps1
Normal file
@@ -0,0 +1,193 @@
|
||||
# Install-ShopdbPrinterDriver.ps1
|
||||
#
|
||||
# Stages a printer driver into the Windows Driver Store and makes it available
|
||||
# to the spooler, silently and offline. Deployable as a DSC Script resource, an
|
||||
# Intune platform script, or a GE-Enforce manifest entry - it needs no user, no
|
||||
# network beyond the driver source, and no vendor setup.exe.
|
||||
#
|
||||
# WHY NOT THE VENDOR INSTALLER: HP's and Xerox's universal drivers are ordinary
|
||||
# INF driver packages. pnputil stages them without a UI, which is the only way
|
||||
# this works on a locked bay with nobody logged in. The vendor bundles add a
|
||||
# wizard and a service nobody wants.
|
||||
#
|
||||
# WHY IT IS SILENT: the signing certificate is added to Trusted Publishers first.
|
||||
# Without that, pnputil prompts to trust the publisher and the install stalls
|
||||
# forever behind a dialog no one will ever see. This mirrors the sequence the
|
||||
# printer installer has used in production.
|
||||
#
|
||||
# IDEMPOTENT: if the spooler already has the driver by name, it does nothing.
|
||||
# Safe to run every enforcement cycle.
|
||||
#
|
||||
# DRIVER NAME: -DriverName must be the name the INF declares, verbatim, e.g.
|
||||
# 'HP Universal Printing PCL 6'. A near-miss fails at Add-PrinterDriver with an
|
||||
# unhelpful error, which is why ShopDB stores the name rather than guessing it.
|
||||
#
|
||||
# SHARE PATHS: on a GE-Enforce site the driver source usually lives on the SFLD
|
||||
# share, which is mounted ONLY during the enforcement cycle. Run this as a
|
||||
# manifest entry inside that cycle, never as its own scheduled task - off-cycle
|
||||
# the path is simply absent and this logs "source not reachable" forever.
|
||||
#
|
||||
# Exits 0 always. A driver that cannot be staged is logged, not thrown: a failed
|
||||
# printer must never fail an enforcement run.
|
||||
|
||||
param(
|
||||
# Exact driver name from the INF, e.g. 'Xerox Global Print Driver PCL6'.
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$DriverName,
|
||||
|
||||
# Folder holding the driver package, or a path to a specific .inf.
|
||||
# UNC or local. This is PrinterDriver.location in ShopDB.
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Source,
|
||||
|
||||
# Stage every .inf found under Source rather than picking one. Universal
|
||||
# driver packages ship several INFs and the needed one is not always
|
||||
# obvious; staging all of them is cheap and avoids guessing.
|
||||
[switch]$AllInf,
|
||||
|
||||
[int]$TimeoutSec = 600
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Continue'
|
||||
|
||||
$logDir = 'C:\Logs\Shopfloor'
|
||||
if (-not (Test-Path $logDir)) {
|
||||
New-Item -ItemType Directory -Path $logDir -Force -ErrorAction SilentlyContinue | Out-Null
|
||||
}
|
||||
$logFile = Join-Path $logDir ('printer-drivers-{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
|
||||
}
|
||||
|
||||
Log "=== Install printer driver: $DriverName ==="
|
||||
|
||||
# Already present: nothing to do. This is the common case on every cycle after
|
||||
# the first, so it is checked before anything touches the share.
|
||||
$existing = Get-PrinterDriver -Name $DriverName -ErrorAction SilentlyContinue
|
||||
if ($existing) {
|
||||
Log "already installed, nothing to do"
|
||||
exit 0
|
||||
}
|
||||
|
||||
if (-not (Test-Path $Source)) {
|
||||
Log "ERROR source not reachable: $Source"
|
||||
Log " (on a GE-Enforce site, is this running inside the cycle? the share is"
|
||||
Log " mounted only for the duration of the run.)"
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Collect the INFs to stage.
|
||||
$infs = @()
|
||||
if ((Get-Item $Source).PSIsContainer) {
|
||||
$found = Get-ChildItem -Path $Source -Filter '*.inf' -Recurse -ErrorAction SilentlyContinue
|
||||
if (-not $AllInf) {
|
||||
# Prefer an INF whose name hints at the architecture in use; otherwise
|
||||
# take them all. Staging a surplus INF costs disk, missing one costs a
|
||||
# site visit.
|
||||
$infs = @($found)
|
||||
} else {
|
||||
$infs = @($found)
|
||||
}
|
||||
} elseif ($Source -like '*.inf') {
|
||||
$infs = @(Get-Item $Source)
|
||||
}
|
||||
|
||||
if (-not $infs -or $infs.Count -eq 0) {
|
||||
Log "ERROR no .inf found under $Source"
|
||||
exit 0
|
||||
}
|
||||
Log "found $($infs.Count) inf file(s)"
|
||||
|
||||
# Trust the package's SIGNER FIRST, or pnputil refuses with "The publisher of an
|
||||
# Authenticode(tm) signed catalog has not yet been established as trusted" - and
|
||||
# on a bay with nobody logged in there is no prompt to answer, so the install
|
||||
# simply never happens.
|
||||
#
|
||||
# The certificate is EXTRACTED from the catalog and added to Trusted Publishers.
|
||||
# Adding the .cat file itself with certutil -addstore is not the same thing: it
|
||||
# stores the catalog, not the publisher, and whether that satisfies pnputil
|
||||
# varies by vendor. It worked for one universal driver and failed for another,
|
||||
# which is a coin toss, not a mechanism.
|
||||
#
|
||||
# Every catalog under the source is trusted, not just the ones beside the first
|
||||
# INF: a universal driver package holds several, and the one that matters is not
|
||||
# predictably the first.
|
||||
$cats = @(Get-ChildItem -Path $Source -Filter '*.cat' -Recurse -ErrorAction SilentlyContinue)
|
||||
$trusted = 0
|
||||
if ($cats.Count -gt 0) {
|
||||
try {
|
||||
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
|
||||
'TrustedPublisher', 'LocalMachine')
|
||||
$store.Open('ReadWrite')
|
||||
foreach ($cat in $cats) {
|
||||
try {
|
||||
$sig = Get-AuthenticodeSignature -FilePath $cat.FullName -ErrorAction Stop
|
||||
if ($sig -and $sig.SignerCertificate) {
|
||||
$store.Add($sig.SignerCertificate)
|
||||
$trusted++
|
||||
} else {
|
||||
Log "WARN no signer certificate on $($cat.Name)"
|
||||
}
|
||||
} catch {
|
||||
Log "WARN could not trust $($cat.Name): $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
$store.Close()
|
||||
} catch {
|
||||
Log "WARN could not open the Trusted Publishers store: $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
Log "trusted $trusted of $($cats.Count) catalog(s)"
|
||||
|
||||
# Stage into the Driver Store. Deliberately WITHOUT /install: that runs a PnP
|
||||
# device-match pass which is pointless for a network printer and slow across a
|
||||
# universal driver's thousands of models. Add-PrinterDriver binds it afterwards.
|
||||
$staged = $false
|
||||
foreach ($inf in $infs) {
|
||||
$null = & pnputil.exe /add-driver $inf.FullName 2>&1
|
||||
# 259 = no more data (nothing new to add), 3010 = success, reboot queued.
|
||||
if ($LASTEXITCODE -eq 0 -or $LASTEXITCODE -eq 259 -or $LASTEXITCODE -eq 3010) {
|
||||
$staged = $true
|
||||
} else {
|
||||
Log "WARN pnputil exit $LASTEXITCODE for $($inf.Name)"
|
||||
}
|
||||
}
|
||||
if (-not $staged) {
|
||||
Log "ERROR nothing staged from $Source"
|
||||
exit 0
|
||||
}
|
||||
Log "staged into the driver store"
|
||||
|
||||
# Make it known to the spooler under the name ShopDB holds.
|
||||
try {
|
||||
Add-PrinterDriver -Name $DriverName -ErrorAction Stop
|
||||
Log "installed: $DriverName"
|
||||
} catch {
|
||||
Log "ERROR Add-PrinterDriver failed for '$DriverName': $($_.Exception.Message)"
|
||||
# Display names live in the INF's [Strings] section as token="Some Name",
|
||||
# referenced elsewhere as %token%. Reading the model lines instead just
|
||||
# reports the manufacturer, which is no help to whoever has to fix this.
|
||||
Log " the name must match the INF verbatim. Names these packages offer:"
|
||||
$offered = @()
|
||||
foreach ($inf in $infs) {
|
||||
$hits = Select-String -Path $inf.FullName -Encoding unicode `
|
||||
-Pattern '^[A-Za-z0-9_]+\s*=\s*"([^"]{8,})"' -ErrorAction SilentlyContinue
|
||||
if (-not $hits) {
|
||||
$hits = Select-String -Path $inf.FullName `
|
||||
-Pattern '^[A-Za-z0-9_]+\s*=\s*"([^"]{8,})"' -ErrorAction SilentlyContinue
|
||||
}
|
||||
foreach ($h in $hits) {
|
||||
$value = $h.Matches[0].Groups[1].Value
|
||||
# A driver name has a space in it; version strings and paths do not.
|
||||
if ($value -match '^[A-Za-z].*\s') { $offered += $value }
|
||||
}
|
||||
}
|
||||
foreach ($name in ($offered | Sort-Object -Unique | Select-Object -First 10)) {
|
||||
Log " $name"
|
||||
}
|
||||
exit 0
|
||||
}
|
||||
|
||||
exit 0
|
||||
202
plugins/printers/client/Install-ShopdbPrinterDrivers.ps1
Normal file
202
plugins/printers/client/Install-ShopdbPrinterDrivers.ps1
Normal file
@@ -0,0 +1,202 @@
|
||||
# Install-ShopdbPrinterDrivers.ps1
|
||||
#
|
||||
# Installs a SITE'S WHOLE DRIVER SET from a manifest, so a bay ends up with every
|
||||
# printer driver it might need in one converging run. Wraps
|
||||
# Install-ShopdbPrinterDriver.ps1, which does one driver.
|
||||
#
|
||||
# DESIGNED FOR DSC / Intune / GE-Enforce. It declares state rather than
|
||||
# performing an install: a driver already present is skipped, so this is safe to
|
||||
# run on a schedule and cheap when there is nothing to do. That is what lets a
|
||||
# DSC Script resource call it from TestScript as well as SetScript.
|
||||
#
|
||||
# THE MANIFEST, not arguments, is the contract. drivers.json lists each driver by
|
||||
# the name its INF declares - what Add-PrinterDriver matches on, verbatim - and
|
||||
# where its package lives. Paths are relative to this script, or absolute (a UNC
|
||||
# path on a site's share is normal).
|
||||
#
|
||||
# EXIT CODE: 0 when every driver in the manifest is present at the end, 1 when
|
||||
# one or more could not be installed. DSC needs a real answer here, unlike the
|
||||
# single-driver script which never fails an enforcement run. The per-driver log
|
||||
# says which and why.
|
||||
#
|
||||
# SHARE PATHS: on a GE-Enforce site the packages usually live on the SFLD share,
|
||||
# which is mounted ONLY during the enforcement cycle. Run this as a manifest
|
||||
# entry inside that cycle, not as its own scheduled task.
|
||||
#
|
||||
# WAVES, because a driver package is not a manifest check. GE-Enforce gives each
|
||||
# PC a start offset of SHA256(hostname) % 5 MINUTES and then repeats every 5
|
||||
# minutes, which was sized for reading a few KB of JSON. A driver set is 100 MB
|
||||
# for the two universals and 226 MB for a full site, so the day an entry lands
|
||||
# the whole fleet pulls it inside one 5-minute window: roughly 30 GB across 300
|
||||
# bays, on the same share every bay needs for everything else. The failure is not
|
||||
# slow drivers, it is a floor that stops converging.
|
||||
#
|
||||
# -WaveStart with -Waves spreads that out. Each PC derives its own wave from its
|
||||
# hostname and does nothing until its turn, so there is no central coordination,
|
||||
# no per-bay configuration and nothing to reconcile afterwards. The hash is the
|
||||
# same idiom Register-GEEnforce.ps1 uses for its offset, SHA-256 rather than MD5
|
||||
# because FIPS-enforced bays disable MD5 outright.
|
||||
#
|
||||
# A bay switched off during its wave installs on its next cycle instead. Late is
|
||||
# a non-event here; the wave sets the earliest moment, not a deadline.
|
||||
#
|
||||
# Unparseable wave arguments FAIL CLOSED - nothing installs, and it says so every
|
||||
# cycle. Failing open would restore precisely the stampede this exists to avoid,
|
||||
# and 30 GB cannot be un-sent, whereas a typo that installs nothing is loud in
|
||||
# the log and fixed in a minute.
|
||||
|
||||
param(
|
||||
# Defaults to drivers.json beside this script.
|
||||
[string]$Manifest = '',
|
||||
|
||||
# Install only these driver names; everything else in the manifest is
|
||||
# ignored. For a bay that needs one driver out of a site-wide set.
|
||||
[string[]]$Only = @(),
|
||||
|
||||
# Report what is missing and change nothing. This is what a DSC TestScript
|
||||
# calls: exit 0 means compliant. A bay whose wave has not arrived is
|
||||
# compliant BY DESIGN - not installed is its desired state today.
|
||||
[switch]$TestOnly,
|
||||
|
||||
# Date the rollout opens, e.g. '2026-08-25' or '2026-08-25 22:00'. Empty
|
||||
# means no gating at all, which is right for imaging time: a bay being built
|
||||
# is one bay, and it should come off the line complete.
|
||||
[string]$WaveStart = '',
|
||||
|
||||
# How many waves to spread the fleet across. 0 or 1 means everyone at once.
|
||||
# 300 bays over 10 daily waves is ~30 bays and ~3 GB a day.
|
||||
[int]$Waves = 0,
|
||||
|
||||
# Wave spacing. Hours finishes a 10-wave rollout inside a day; Days is the
|
||||
# cautious setting when nobody is watching the share.
|
||||
[ValidateSet('Days', 'Hours')]
|
||||
[string]$WaveUnit = 'Days',
|
||||
|
||||
# Pilot bays skip the gate. Use this to prove one bay before the fleet.
|
||||
[switch]$IgnoreWave
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Continue'
|
||||
|
||||
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
if (-not $Manifest) { $Manifest = Join-Path $here 'drivers.json' }
|
||||
|
||||
$logDir = 'C:\Logs\Shopfloor'
|
||||
if (-not (Test-Path $logDir)) {
|
||||
New-Item -ItemType Directory -Path $logDir -Force -ErrorAction SilentlyContinue | Out-Null
|
||||
}
|
||||
$logFile = Join-Path $logDir ('printer-drivers-{0}.log' -f (Get-Date -Format 'yyyyMMdd'))
|
||||
function Log([string]$msg) {
|
||||
$ts = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
|
||||
"$ts [set] $msg" | Tee-Object -FilePath $logFile -Append | Out-Null
|
||||
}
|
||||
|
||||
# The gate runs BEFORE the manifest is read, because the manifest lives on the
|
||||
# share too. A bay that is not due this wave must not touch the share at all -
|
||||
# reading it is cheap, but 300 bays deciding to read it in the same 5 minutes is
|
||||
# how this whole problem starts.
|
||||
if ($WaveStart -and -not $IgnoreWave) {
|
||||
$start = [datetime]::MinValue
|
||||
if (-not [datetime]::TryParse($WaveStart, [ref]$start)) {
|
||||
Log "ERROR -WaveStart '$WaveStart' is not a date. Refusing to install."
|
||||
Log ' (failing closed on purpose: guessing here would release the whole fleet at once)'
|
||||
exit 1
|
||||
}
|
||||
|
||||
$waveCount = $Waves
|
||||
if ($waveCount -lt 1) { $waveCount = 1 }
|
||||
|
||||
# Same hostname hash as the enforcer's own start offset, so a bay's wave is
|
||||
# stable for the life of its name: it cannot drift between cycles, and a
|
||||
# rerun never moves a PC into a different wave.
|
||||
$hostHash = [System.BitConverter]::ToUInt32(
|
||||
[System.Security.Cryptography.SHA256]::Create().ComputeHash(
|
||||
[System.Text.Encoding]::UTF8.GetBytes([System.Environment]::MachineName)), 0)
|
||||
$wave = [int]($hostHash % [uint32]$waveCount)
|
||||
|
||||
if ($WaveUnit -eq 'Hours') { $due = $start.AddHours($wave) }
|
||||
else { $due = $start.AddDays($wave) }
|
||||
|
||||
if ((Get-Date) -lt $due) {
|
||||
Log ("wave {0} of {1} for {2}; not due until {3}. Nothing to do." -f `
|
||||
$wave, $waveCount, [System.Environment]::MachineName,
|
||||
$due.ToString('yyyy-MM-dd HH:mm'))
|
||||
exit 0
|
||||
}
|
||||
Log ("wave {0} of {1} opened {2}; proceeding" -f `
|
||||
$wave, $waveCount, $due.ToString('yyyy-MM-dd HH:mm'))
|
||||
}
|
||||
|
||||
if (-not (Test-Path $Manifest)) {
|
||||
Log "ERROR manifest not found: $Manifest"
|
||||
exit 1
|
||||
}
|
||||
|
||||
try {
|
||||
$config = Get-Content -Raw -Path $Manifest | ConvertFrom-Json
|
||||
} catch {
|
||||
Log "ERROR manifest is not valid JSON: $($_.Exception.Message)"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$wanted = @($config.drivers)
|
||||
if ($Only.Count -gt 0) {
|
||||
$wanted = @($wanted | Where-Object { $Only -contains $_.drivername })
|
||||
}
|
||||
if ($wanted.Count -eq 0) {
|
||||
Log "nothing to do: the manifest selects no drivers"
|
||||
exit 0
|
||||
}
|
||||
|
||||
$single = Join-Path $here 'Install-ShopdbPrinterDriver.ps1'
|
||||
if (-not (Test-Path $single)) {
|
||||
Log "ERROR Install-ShopdbPrinterDriver.ps1 is not beside this script"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$missing = @()
|
||||
foreach ($driver in $wanted) {
|
||||
$name = $driver.drivername
|
||||
if (-not $name) { continue }
|
||||
|
||||
if (Get-PrinterDriver -Name $name -ErrorAction SilentlyContinue) {
|
||||
Log "present: $name"
|
||||
continue
|
||||
}
|
||||
|
||||
if ($TestOnly) {
|
||||
Log "MISSING: $name"
|
||||
$missing += $name
|
||||
continue
|
||||
}
|
||||
|
||||
# Relative paths are resolved against the package, so the whole thing can be
|
||||
# copied anywhere - a share, C:\ProgramData, an Intune staging folder - and
|
||||
# still find its own payloads.
|
||||
$path = $driver.path
|
||||
if ($path -and -not [System.IO.Path]::IsPathRooted($path)) {
|
||||
$path = Join-Path $here $path
|
||||
}
|
||||
if (-not $path -or -not (Test-Path $path)) {
|
||||
Log "ERROR package not found for '$name': $path"
|
||||
$missing += $name
|
||||
continue
|
||||
}
|
||||
|
||||
Log "installing: $name"
|
||||
& $single -DriverName $name -Source $path | Out-Null
|
||||
|
||||
if (Get-PrinterDriver -Name $name -ErrorAction SilentlyContinue) {
|
||||
Log "installed: $name"
|
||||
} else {
|
||||
Log "FAILED: $name (see the per-driver lines above)"
|
||||
$missing += $name
|
||||
}
|
||||
}
|
||||
|
||||
if ($missing.Count -gt 0) {
|
||||
Log ("not present: {0}" -f ($missing -join ', '))
|
||||
exit 1
|
||||
}
|
||||
Log "all $($wanted.Count) driver(s) present"
|
||||
exit 0
|
||||
314
plugins/printers/client/Report-PrintersToShopDB.ps1
Normal file
314
plugins/printers/client/Report-PrintersToShopDB.ps1
Normal 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
|
||||
379
plugins/printers/client/Set-ShopdbPrinters.ps1
Normal file
379
plugins/printers/client/Set-ShopdbPrinters.ps1
Normal file
@@ -0,0 +1,379 @@
|
||||
# Set-ShopdbPrinters.ps1
|
||||
#
|
||||
# Makes this PC's printers match what ShopDB says the bay should have. Asks
|
||||
# GET /api/printers/for-host/<hostname> and creates any queue that is missing.
|
||||
#
|
||||
# WHY THE ASSIGNMENT IS NOT ON THIS PC: it is on the MACHINE, and reaches
|
||||
# whichever PC controls it. A reimaged or swapped box inherits the bay's printers
|
||||
# with nothing saved off the old one - the asset register is the backup.
|
||||
#
|
||||
# CONVERGES, does not install. A queue that already exists is left alone, so this
|
||||
# is cheap to run every enforcement cycle and safe to run twice.
|
||||
#
|
||||
# NEVER REMOVES A QUEUE. If a printer disappears from the response - because the
|
||||
# API had a bad minute, or someone unassigned it - the bay keeps printing. Taking
|
||||
# printers away from a working bay because of a transient error is the one
|
||||
# failure this must not have.
|
||||
#
|
||||
# DRIVERS ARE NOT FETCHED HERE. Install-ShopdbPrinterDrivers.ps1 stages the site's
|
||||
# set in the common scope, once per bay. A queue is created against a driver that
|
||||
# is already present; if it is not, that is logged and the printer is skipped,
|
||||
# because downloading 48 MB while somebody waits to print is the wrong moment.
|
||||
#
|
||||
# THE DEFAULT PRINTER IS PER USER. This runs as SYSTEM and cannot set it for the
|
||||
# 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(
|
||||
# ShopDB base URL. Empty resolves from HKLM:\SOFTWARE\GE\ShopDB BaseUrl,
|
||||
# written by Install-GEEnforce.ps1 and already present wherever this runs.
|
||||
[string]$BaseUrl = '',
|
||||
|
||||
# Defaults to this machine's name, which is what the collector upserts by.
|
||||
[string]$Hostname = $env:COMPUTERNAME,
|
||||
|
||||
[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
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Continue'
|
||||
[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 ('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
|
||||
}
|
||||
|
||||
# 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) {
|
||||
foreach ($path in @($REGPATH, 'HKLM:\SOFTWARE\WOW6432Node\GE\ShopDB')) {
|
||||
try {
|
||||
if (Test-Path $path) {
|
||||
$value = [string](Get-ItemProperty -Path $path -Name BaseUrl -ErrorAction Stop).BaseUrl
|
||||
if ($value -and $value.Trim()) { $BaseUrl = $value.Trim(); break }
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
if (-not $BaseUrl) {
|
||||
Log 'ERROR no ShopDB URL (HKLM:\SOFTWARE\GE\ShopDB BaseUrl or -BaseUrl). Skipping.'
|
||||
exit 0
|
||||
}
|
||||
|
||||
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
|
||||
} catch {
|
||||
# An unreachable server means "no information", not "no printers". Changing
|
||||
# nothing is the only safe response.
|
||||
Log "ERROR could not read $url : $($_.Exception.Message)"
|
||||
exit 0
|
||||
}
|
||||
|
||||
$payload = $response.data
|
||||
if ($null -eq $payload) { $payload = $response }
|
||||
$wanted = @($payload.printers)
|
||||
$defaultid = $payload.defaultprinterid
|
||||
|
||||
if ($wanted.Count -eq 0) {
|
||||
Log 'nothing assigned to this host'
|
||||
exit 0
|
||||
}
|
||||
Log "assigned: $($wanted.Count) printer(s)"
|
||||
|
||||
function Ensure-Port([string]$address) {
|
||||
$portname = 'IP_' + $address
|
||||
if (-not (Get-PrinterPort -Name $portname -ErrorAction SilentlyContinue)) {
|
||||
Add-PrinterPort -Name $portname -PrinterHostAddress $address -ErrorAction Stop
|
||||
Log "port: $portname"
|
||||
}
|
||||
return $portname
|
||||
}
|
||||
|
||||
function Repair-Queue($queue, [string]$address, [string]$drivername) {
|
||||
$name = $queue.Name
|
||||
|
||||
# The address ShopDB holds is the truth about where the printer IS. A queue
|
||||
# left pointing at the old address prints into the void, and looks fine.
|
||||
if ($address) {
|
||||
$wantedport = 'IP_' + $address
|
||||
if ($queue.PortName -ne $wantedport) {
|
||||
if ($WhatIfOnly) {
|
||||
Log "WOULD repoint $name : $($queue.PortName) -> $wantedport"
|
||||
} else {
|
||||
try {
|
||||
$portname = Ensure-Port $address
|
||||
Set-Printer -Name $name -PortName $portname -ErrorAction Stop
|
||||
Log "repointed $name : $($queue.PortName) -> $portname"
|
||||
} catch {
|
||||
Log "ERROR repointing ${name}: $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# A queue built on a driver the site has moved off keeps using it forever.
|
||||
# Only corrected when the wanted driver is actually staged - swapping a queue
|
||||
# onto a driver that is not installed would break a working printer.
|
||||
if ($drivername -and $queue.DriverName -ne $drivername) {
|
||||
if (-not (Get-PrinterDriver -Name $drivername -ErrorAction SilentlyContinue)) {
|
||||
Log "SKIP driver fix for $name : '$drivername' is not staged"
|
||||
} elseif ($WhatIfOnly) {
|
||||
Log "WOULD re-driver $name : $($queue.DriverName) -> $drivername"
|
||||
} else {
|
||||
try {
|
||||
Set-Printer -Name $name -DriverName $drivername -ErrorAction Stop
|
||||
Log "re-drivered $name : $($queue.DriverName) -> $drivername"
|
||||
} catch {
|
||||
Log "ERROR re-drivering ${name}: $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($queue.PortName -eq ('IP_' + $address) -and
|
||||
($drivername -eq '' -or $queue.DriverName -eq $drivername)) {
|
||||
Log "present: $name"
|
||||
}
|
||||
}
|
||||
|
||||
$existing = @{}
|
||||
foreach ($queue in (Get-Printer -ErrorAction SilentlyContinue)) {
|
||||
$existing[$queue.Name] = $queue
|
||||
}
|
||||
|
||||
$defaultname = ''
|
||||
foreach ($printer in $wanted) {
|
||||
$name = $printer.queuename
|
||||
if (-not $name) { continue }
|
||||
if ($printer.printerid -eq $defaultid) { $defaultname = $name }
|
||||
|
||||
$address = $printer.hostname
|
||||
if (-not $address) { $address = $printer.ipaddress }
|
||||
$drivername = $printer.drivername
|
||||
|
||||
if ($existing.ContainsKey($name)) {
|
||||
# A queue with the right NAME can still be wrong: pointing at a printer
|
||||
# that has moved, or built on a driver that has since been replaced.
|
||||
# Absence used to be the only thing fixed, so a bay with a stale queue
|
||||
# looked converged and printed to the wrong device.
|
||||
#
|
||||
# Corrected IN PLACE with Set-Printer, never removed and recreated: the
|
||||
# queue keeps its name, its sharing, its permissions, and whoever has it
|
||||
# as their default keeps it.
|
||||
Repair-Queue $existing[$name] $address $drivername
|
||||
continue
|
||||
}
|
||||
|
||||
if (-not $address) {
|
||||
Log "SKIP $name : no hostname or IP to point a port at"
|
||||
continue
|
||||
}
|
||||
|
||||
if (-not $drivername) {
|
||||
Log "SKIP $name : ShopDB has no driver name for it"
|
||||
continue
|
||||
}
|
||||
if (-not (Get-PrinterDriver -Name $drivername -ErrorAction SilentlyContinue)) {
|
||||
# Deliberately not fetched here - see the header.
|
||||
Log "SKIP $name : driver '$drivername' is not staged on this PC"
|
||||
continue
|
||||
}
|
||||
|
||||
if ($WhatIfOnly) {
|
||||
Log "WOULD create: $name -> $address ($drivername)"
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
$portname = Ensure-Port $address
|
||||
Add-Printer -Name $name -DriverName $drivername -PortName $portname -ErrorAction Stop
|
||||
Log "created: $name -> $address ($drivername)"
|
||||
} catch {
|
||||
Log "ERROR creating ${name}: $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
|
||||
# The default is recorded, not applied: this process is SYSTEM and the setting
|
||||
# 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"
|
||||
} else {
|
||||
try {
|
||||
if (-not (Test-Path $REGPATH)) { New-Item -Path $REGPATH -Force | Out-Null }
|
||||
Set-ItemProperty -Path $REGPATH -Name DefaultPrinter -Value $defaultname
|
||||
Log "default recorded for the logon task: $defaultname"
|
||||
} catch {
|
||||
Log "ERROR recording the default: $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Log 'no default assigned'
|
||||
}
|
||||
|
||||
exit 0
|
||||
35
plugins/printers/client/drivers.example.json
Normal file
35
plugins/printers/client/drivers.example.json
Normal file
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"_comment": "Driver set for a site. Each entry names a driver EXACTLY as its INF declares it (what Add-PrinterDriver matches on) and where its package lives, relative to the package root or as an absolute UNC path. Copy to drivers.json and edit for the site.",
|
||||
"drivers": [
|
||||
{
|
||||
"drivername": "HP Universal Printing PS",
|
||||
"path": "drivers/hp_upd_ps",
|
||||
"covers": "HP office printers (universal)"
|
||||
},
|
||||
{
|
||||
"drivername": "Xerox Global Print Driver PCL6",
|
||||
"path": "drivers/xerox_gpd",
|
||||
"covers": "Xerox office printers (universal)"
|
||||
},
|
||||
{
|
||||
"drivername": "HP DesignJet T1700dr V4",
|
||||
"path": "drivers/hp_designjet",
|
||||
"covers": "DesignJet T1700 / T1700dr plotters"
|
||||
},
|
||||
{
|
||||
"drivername": "ZDesigner ZT411-300dpi ZPL",
|
||||
"path": "drivers/zebra_zt411",
|
||||
"covers": "Zebra ZT411 label printers"
|
||||
},
|
||||
{
|
||||
"drivername": "EPSON TM-C3500",
|
||||
"path": "drivers/epson_tmc3500",
|
||||
"covers": "Epson ColorWorks C3500 label printers"
|
||||
},
|
||||
{
|
||||
"drivername": "DTC4500e Card Printer",
|
||||
"path": "drivers/hid_dtc4500e",
|
||||
"covers": "HID FARGO DTC4500e card printer"
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user