From 6dcf832aceede5a2fddd8b5e8760a6abc9c217ee Mon Sep 17 00:00:00 2001 From: cproudlock Date: Sat, 18 Apr 2026 10:16:20 -0400 Subject: [PATCH] Keyence ongoing-update enforcer (tsgwp00525 share pattern) Adds a CMM-style logon enforcer so VR-6000 updates push fleet-wide without re-imaging. - keyence-manifest.json: declares VR-6000 MSI (ProductCode-keyed) and KEYENCE VR USB driver (pnputil-keyed). Single source of truth for both imaging-time and ongoing-enforcement paths. - lib/Install-FromManifest.ps1: forked from CMM/lib; adds DetectionMethod "pnputil" (regex-matches `pnputil /enum-drivers` output) and Type "INF" (invokes `pnputil /add-driver /install`). Everything else unchanged so CMM-style error parsing + MSI log scanning carry over. - Keyence-Enforce.ps1: forked from CMM-Enforce.ps1. SYSTEM scheduled task, logon trigger, mounts tsgwp00525 SFLD share with creds from HKLM:\SOFTWARE\GE\SFLD\Credentials (provisioned by Azure DSC), hands off to Install-FromManifest against the share manifest. - 09-Setup-Keyence.ps1: rewritten around the manifest. Runs Install-FromManifest at imaging time, stages runtime scripts to C:\Program Files\GE\Keyence, registers "GE Keyence Enforce" scheduled task. Idempotent. - site-config.json: add keyenceSharePath to the Keyence profile pointing at \\tsgwp00525\shared\dt\shopfloor\keyence\machineapps. To push a new VR-6000 version: drop the new MSI + updated manifest on the tsgwp00525 share, every Keyence PC upgrades on next logon. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../Keyence/09-Setup-Keyence.ps1 | 202 +++++------ .../Keyence/Keyence-Enforce.ps1 | 126 +++++++ .../Keyence/keyence-manifest.json | 25 ++ .../Keyence/lib/Install-FromManifest.ps1 | 327 ++++++++++++++++++ playbook/shopfloor-setup/site-config.json | 3 +- 5 files changed, 584 insertions(+), 99 deletions(-) create mode 100644 playbook/shopfloor-setup/Keyence/Keyence-Enforce.ps1 create mode 100644 playbook/shopfloor-setup/Keyence/keyence-manifest.json create mode 100644 playbook/shopfloor-setup/Keyence/lib/Install-FromManifest.ps1 diff --git a/playbook/shopfloor-setup/Keyence/09-Setup-Keyence.ps1 b/playbook/shopfloor-setup/Keyence/09-Setup-Keyence.ps1 index 8c8c645..e9ac0b8 100644 --- a/playbook/shopfloor-setup/Keyence/09-Setup-Keyence.ps1 +++ b/playbook/shopfloor-setup/Keyence/09-Setup-Keyence.ps1 @@ -1,46 +1,44 @@ # 09-Setup-Keyence.ps1 - Keyence type setup (runs during shopfloor-setup phase). # -# Installs the VR-6000 Series Software MSI and the KEYENCE VR Series USB driver -# package. Both payloads ship inside this directory (shopfloor-setup\Keyence\) -# and are staged by startnet.cmd during WinPE, so they exist locally on disk -# when this script runs - no share mapping required. +# Performs one-shot imaging-time install and then registers the ongoing +# enforcer. Mirrors CMM's pattern. # -# Layout (sibling to this .ps1): +# Sequence: +# 1. Run Install-FromManifest against the staged bundle in $PSScriptRoot. +# Installs VR-6000 Series Software MSI + KEYENCE VR Series USB driver. +# 2. Stage Install-FromManifest.ps1 + Keyence-Enforce.ps1 + keyence-manifest.json +# to C:\Program Files\GE\Keyence so the scheduled task has them post-imaging. +# 3. Register "GE Keyence Enforce" scheduled task (SYSTEM, logon trigger). +# It mounts the tsgwp00525 share, reads the manifest there, and upgrades +# anything whose detection falls out of sync. Credentials for the share +# arrive via Azure DSC writing to HKLM:\SOFTWARE\GE\SFLD\Credentials. +# +# Layout at $PSScriptRoot (xcopied by startnet.cmd only for PCTYPE=Keyence): +# keyence-manifest.json +# 09-Setup-Keyence.ps1 (this file) +# Keyence-Enforce.ps1 (staged to C:\Program Files\GE\Keyence) +# lib\Install-FromManifest.ps1 (staged alongside) # installers\VR-6000 Series Software.msi -# drivers\keyence_vr_series.inf -# drivers\KEYENCE_VR_SERIES.cat -# drivers\amd64\WdfCoInstaller01009.dll -# drivers\amd64\WinUsbCoinstaller2.dll -# -# Prereqs (installed earlier by 00-PreInstall-MachineApps.ps1 via preinstall.json): -# - Microsoft Visual C++ 2010 x86 + x64 -# - Microsoft Visual C++ 2013 x86 + x64 (Min + Add) -# - Microsoft Visual C++ 2017/2022 x86 (UCRT covers 2015-2022) -# -# Idempotent: skips the MSI if the product GUID is already registered, skips -# the driver if the package is already in the DriverStore. +# drivers\keyence_vr_series.inf (+ cat + amd64\{Wdf,WinUsb}CoInstaller*.dll) # # Log: C:\Logs\Keyence\09-Setup-Keyence.log +# C:\Logs\Keyence\install.log (written by Install-FromManifest) $ErrorActionPreference = 'Continue' -$logDir = 'C:\Logs\Keyence' -$transcriptLog = Join-Path $logDir '09-Setup-Keyence.log' +$manifestPath = Join-Path $PSScriptRoot 'keyence-manifest.json' +$libSource = Join-Path $PSScriptRoot 'lib\Install-FromManifest.ps1' +$enforceSource = Join-Path $PSScriptRoot 'Keyence-Enforce.ps1' -$installerDir = Join-Path $PSScriptRoot 'installers' -$msiPath = Join-Path $installerDir 'VR-6000 Series Software.msi' -$msiLog = Join-Path $logDir 'VR-6000-msiexec.log' -$driverDir = Join-Path $PSScriptRoot 'drivers' -$driverInf = Join-Path $driverDir 'keyence_vr_series.inf' +$runtimeRoot = 'C:\Program Files\GE\Keyence' +$runtimeLibDir = Join-Path $runtimeRoot 'lib' +$runtimeLib = Join-Path $runtimeLibDir 'Install-FromManifest.ps1' +$runtimeEnforce = Join-Path $runtimeRoot 'Keyence-Enforce.ps1' +$runtimeManifest= Join-Path $runtimeRoot 'keyence-manifest.json' -# Product registration - ProductCode read from the MSI via msiinfo: must match -# the value baked in, so idempotency works after a successful install. -$productCode = '{058E7194-BDF8-4FA2-9D69-978BB0F25214}' -$expectedVersion = '4.3.7' -$uninstallRegPaths = @( - "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$productCode", - "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\$productCode" -) +$logDir = 'C:\Logs\Keyence' +$installLog = Join-Path $logDir 'install.log' +$transcriptLog = Join-Path $logDir '09-Setup-Keyence.log' if (-not (Test-Path $logDir)) { New-Item -Path $logDir -ItemType Directory -Force | Out-Null @@ -55,82 +53,90 @@ function Write-KeyenceLog { } Write-KeyenceLog "================================================================" -Write-KeyenceLog "=== Keyence Setup session start (PID $PID) ===" +Write-KeyenceLog "=== Keyence Setup (imaging-time) session start (PID $PID) ===" Write-KeyenceLog "Running as: $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)" Write-KeyenceLog "Script root: $PSScriptRoot" Write-KeyenceLog "================================================================" -# --- Detection: skip MSI if already installed at expected version --- -$msiAlreadyInstalled = $false -foreach ($regPath in $uninstallRegPaths) { - if (Test-Path $regPath) { - $installed = (Get-ItemProperty $regPath -ErrorAction SilentlyContinue).DisplayVersion - if ($installed -eq $expectedVersion) { - Write-KeyenceLog "MSI already installed (DisplayVersion=$installed at $regPath) - skipping" - $msiAlreadyInstalled = $true - break - } else { - Write-KeyenceLog "MSI registered but at version '$installed' (expected $expectedVersion) - will reinstall" "WARN" - } - } -} - -# --- Install MSI --- -if (-not $msiAlreadyInstalled) { - if (-not (Test-Path $msiPath)) { - Write-KeyenceLog "MSI not found at $msiPath - aborting MSI install" "ERROR" +# Diagnostic dump +foreach ($file in @('pc-type.txt','pc-subtype.txt','machine-number.txt')) { + $path = "C:\Enrollment\$file" + if (Test-Path -LiteralPath $path) { + $content = (Get-Content -LiteralPath $path -First 1 -ErrorAction SilentlyContinue).Trim() + Write-KeyenceLog " $file = $content" } else { - $msiSize = [math]::Round((Get-Item $msiPath).Length / 1MB, 1) - Write-KeyenceLog "Installing VR-6000 Series Software MSI ($msiSize MB)" - $msiArgs = @( - '/i', "`"$msiPath`"", - '/qn', '/norestart', - 'ALLUSERS=1', 'REBOOT=ReallySuppress', - '/L*v', "`"$msiLog`"" - ) - $sw = [Diagnostics.Stopwatch]::StartNew() - $proc = Start-Process -FilePath 'msiexec.exe' -ArgumentList $msiArgs -Wait -PassThru -NoNewWindow - $sw.Stop() - # msiexec exit codes we tolerate: 0 = success, 3010 = success w/ reboot recommended - if ($proc.ExitCode -eq 0 -or $proc.ExitCode -eq 3010) { - Write-KeyenceLog "MSI install succeeded (exit=$($proc.ExitCode), elapsed=$([int]$sw.Elapsed.TotalSeconds)s)" - } else { - Write-KeyenceLog "MSI install FAILED (exit=$($proc.ExitCode)). See $msiLog" "ERROR" - } + Write-KeyenceLog " $file = (not present)" } } -# --- Detection: skip driver if already in DriverStore --- -$driverAlreadyStaged = $false +# ============================================================================ +# Step 1: Install via manifest (imaging-time) +# ============================================================================ +if (-not (Test-Path $manifestPath)) { + Write-KeyenceLog "keyence-manifest.json not found at $manifestPath" "ERROR" +} elseif (-not (Test-Path $libSource)) { + Write-KeyenceLog "Install-FromManifest.ps1 not found at $libSource" "ERROR" +} else { + Write-KeyenceLog "Running Install-FromManifest (InstallerRoot=$PSScriptRoot)" + & $libSource -ManifestPath $manifestPath -InstallerRoot $PSScriptRoot -LogFile $installLog + $rc = $LASTEXITCODE + Write-KeyenceLog "Install-FromManifest returned $rc" +} + +# ============================================================================ +# Step 2: Stage runtime scripts to C:\Program Files\GE\Keyence +# ============================================================================ +# These survive past any bootstrap cleanup so the logon-triggered scheduled +# task can run them. The manifest is staged too as a fallback for the first +# logon if the share is unreachable. +Write-KeyenceLog "Staging runtime scripts to $runtimeRoot" +foreach ($dir in @($runtimeRoot, $runtimeLibDir)) { + if (-not (Test-Path $dir)) { + New-Item -Path $dir -ItemType Directory -Force | Out-Null + } +} +Copy-Item -Path $libSource -Destination $runtimeLib -Force +Copy-Item -Path $enforceSource -Destination $runtimeEnforce -Force +Copy-Item -Path $manifestPath -Destination $runtimeManifest -Force + +# ============================================================================ +# Step 3: Register "GE Keyence Enforce" scheduled task (logon trigger, SYSTEM) +# ============================================================================ +$taskName = 'GE Keyence Enforce' + +# Drop any stale version first so re-imaging is idempotent. +$existing = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue +if ($existing) { + Write-KeyenceLog "Removing existing scheduled task '$taskName'" + Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue +} + +Write-KeyenceLog "Registering scheduled task '$taskName' (logon trigger, SYSTEM)" try { - $pnpOut = & pnputil.exe /enum-drivers 2>&1 | Out-String - if ($pnpOut -match 'keyence_vr_series\.inf') { - Write-KeyenceLog "Keyence USB driver already in DriverStore - skipping" - $driverAlreadyStaged = $true - } -} catch { - Write-KeyenceLog "pnputil /enum-drivers failed ($($_.Exception.Message)); attempting install anyway" "WARN" -} + $action = New-ScheduledTaskAction ` + -Execute 'powershell.exe' ` + -Argument "-NoProfile -ExecutionPolicy Bypass -File `"$runtimeEnforce`"" -# --- Install driver --- -if (-not $driverAlreadyStaged) { - if (-not (Test-Path $driverInf)) { - Write-KeyenceLog "Driver INF not found at $driverInf - aborting driver install" "ERROR" - } else { - Write-KeyenceLog "Adding KEYENCE VR Series USB driver to DriverStore via pnputil" - $pnp = Start-Process -FilePath 'pnputil.exe' ` - -ArgumentList '/add-driver', "`"$driverInf`"", '/install' ` - -Wait -PassThru -NoNewWindow ` - -RedirectStandardOutput (Join-Path $logDir 'pnputil-stdout.log') ` - -RedirectStandardError (Join-Path $logDir 'pnputil-stderr.log') - # pnputil exit codes: 0 = ok, 3010 = ok (reboot recommended), - # 259 = ERROR_NO_MORE_ITEMS (no INFs matched) - if ($pnp.ExitCode -eq 0 -or $pnp.ExitCode -eq 3010) { - Write-KeyenceLog "Driver install succeeded (exit=$($pnp.ExitCode))" - } else { - Write-KeyenceLog "Driver install FAILED (exit=$($pnp.ExitCode))" "ERROR" - } - } + $trigger = New-ScheduledTaskTrigger -AtLogOn + $principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest + $settings = New-ScheduledTaskSettingsSet ` + -AllowStartIfOnBatteries ` + -DontStopIfGoingOnBatteries ` + -StartWhenAvailable ` + -ExecutionTimeLimit (New-TimeSpan -Hours 1) ` + -MultipleInstances IgnoreNew + + Register-ScheduledTask ` + -TaskName $taskName ` + -Action $action ` + -Trigger $trigger ` + -Principal $principal ` + -Settings $settings ` + -Description 'GE Keyence: enforce VR-6000 Series Software + USB driver against tsgwp00525 SFLD share on user logon' | Out-Null + + Write-KeyenceLog "Scheduled task registered" +} catch { + Write-KeyenceLog "Failed to register scheduled task: $_" "ERROR" } Write-KeyenceLog "================================================================" diff --git a/playbook/shopfloor-setup/Keyence/Keyence-Enforce.ps1 b/playbook/shopfloor-setup/Keyence/Keyence-Enforce.ps1 new file mode 100644 index 0000000..4ee3ab5 --- /dev/null +++ b/playbook/shopfloor-setup/Keyence/Keyence-Enforce.ps1 @@ -0,0 +1,126 @@ +# Keyence-Enforce.ps1 - On-logon Keyence app enforcer (mini-DSC side). +# +# Runs under a SYSTEM scheduled task triggered at user logon. Mounts the +# tsgwp00525 SFLD share using creds written to HKLM by Azure DSC, reads +# keyence-manifest.json from the share, and hands off to Install-FromManifest.ps1 +# which installs anything whose detection fails. +# +# When Keyence ships a VR-6000 update: drop the new MSI (or driver package) +# in the tsgwp00525 share alongside a bumped keyence-manifest.json, and every +# Keyence PC upgrades on its next logon. +# +# Same graceful-degradation pattern as CMM-Enforce: SFLD creds missing, share +# unreachable, or per-app install failure all log and continue. Task never +# returns non-zero so the "last run" UI stays clean; read the log for truth. + +$ErrorActionPreference = 'Continue' + +$installRoot = 'C:\Program Files\GE\Keyence' +$libPath = Join-Path $installRoot 'lib\Install-FromManifest.ps1' +$logDir = 'C:\Logs\Keyence' +$logFile = Join-Path $logDir ('enforce-{0}.log' -f (Get-Date -Format 'yyyyMMdd')) +$driveLetter = 'S:' + +if (-not (Test-Path $logDir)) { + New-Item -Path $logDir -ItemType Directory -Force | Out-Null +} + +function Write-EnforceLog { + param([string]$Message, [string]$Level = 'INFO') + $line = "[{0}] [{1}] {2}" -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Level, $Message + Write-Host $line + Add-Content -Path $logFile -Value $line -ErrorAction SilentlyContinue +} + +Write-EnforceLog "================================================================" +Write-EnforceLog "=== Keyence-Enforce session start (PID $PID, user $env:USERNAME) ===" +Write-EnforceLog "================================================================" + +# --- Load site-config + pcProfile (for keyenceSharePath) --- +# Dot-source the same Get-PCProfile.ps1 used during imaging. It populates +# $pcProfile/$siteConfig script variables from C:\Enrollment\site-config.json. +$getProfileScript = 'C:\Enrollment\shopfloor-setup\Shopfloor\lib\Get-PCProfile.ps1' +if (-not (Test-Path $getProfileScript)) { + Write-EnforceLog "Get-PCProfile.ps1 not found at $getProfileScript - is this a Keyence PC?" "ERROR" + exit 0 +} +. $getProfileScript + +if (-not $pcProfile -or -not $pcProfile.keyenceSharePath) { + Write-EnforceLog "No keyenceSharePath in profile - nothing to enforce" "WARN" + exit 0 +} + +$sharePath = $pcProfile.keyenceSharePath +Write-EnforceLog "Share: $sharePath" + +# --- SFLD credential lookup (written by Azure DSC post-PPKG). Bail gracefully +# if the creds are not yet provisioned; next logon will retry. --- +function Get-SFLDCredential { + param([string]$ServerName) + $basePath = 'HKLM:\SOFTWARE\GE\SFLD\Credentials' + if (-not (Test-Path $basePath)) { return $null } + + foreach ($entry in Get-ChildItem -Path $basePath -ErrorAction SilentlyContinue) { + $props = Get-ItemProperty -Path $entry.PSPath -ErrorAction SilentlyContinue + if (-not $props -or -not $props.TargetHost) { continue } + if ($props.TargetHost -eq $ServerName -or + $props.TargetHost -like "$ServerName.*" -or + $ServerName -like "$($props.TargetHost).*") { + return @{ + Username = $props.Username + Password = $props.Password + TargetHost = $props.TargetHost + KeyName = $entry.PSChildName + } + } + } + return $null +} + +$serverName = ($sharePath -replace '^\\\\', '') -split '\\' | Select-Object -First 1 +$cred = Get-SFLDCredential -ServerName $serverName + +if (-not $cred -or -not $cred.Username -or -not $cred.Password) { + Write-EnforceLog "No SFLD credential for $serverName yet (Azure DSC has not provisioned it) - will retry at next logon" + exit 0 +} + +Write-EnforceLog "Credential: $($cred.KeyName) (user: $($cred.Username))" + +# --- Mount the share --- +net use $driveLetter /delete /y 2>$null | Out-Null + +$netResult = & net use $driveLetter $sharePath /user:$($cred.Username) $($cred.Password) /persistent:no 2>&1 +if ($LASTEXITCODE -ne 0) { + Write-EnforceLog "net use failed (exit $LASTEXITCODE): $netResult" "WARN" + Write-EnforceLog "Share unreachable - probably off-network. Will retry at next logon." + exit 0 +} +Write-EnforceLog "Mounted $sharePath as $driveLetter" + +try { + $manifestOnShare = Join-Path $driveLetter 'keyence-manifest.json' + if (-not (Test-Path $manifestOnShare)) { + Write-EnforceLog "keyence-manifest.json not found on share - nothing to enforce" "WARN" + return + } + + if (-not (Test-Path $libPath)) { + Write-EnforceLog "Install-FromManifest.ps1 not found at $libPath" "ERROR" + return + } + + Write-EnforceLog "Handing off to Install-FromManifest.ps1 (InstallerRoot=$driveLetter)" + & $libPath -ManifestPath $manifestOnShare -InstallerRoot $driveLetter -LogFile $logFile + $rc = $LASTEXITCODE + Write-EnforceLog "Install-FromManifest returned $rc" +} +finally { + net use $driveLetter /delete /y 2>$null | Out-Null + Write-EnforceLog "Unmounted $driveLetter" + Write-EnforceLog "=== Keyence-Enforce session end ===" +} + +# Always return 0 so the scheduled task never shows "last run failed" noise. +exit 0 diff --git a/playbook/shopfloor-setup/Keyence/keyence-manifest.json b/playbook/shopfloor-setup/Keyence/keyence-manifest.json new file mode 100644 index 0000000..f75af22 --- /dev/null +++ b/playbook/shopfloor-setup/Keyence/keyence-manifest.json @@ -0,0 +1,25 @@ +{ + "Version": "1.0", + "_comment": "Keyence machine-app manifest. Consumed by both 09-Setup-Keyence.ps1 (at imaging time, reading from the in-repo shopfloor-setup/Keyence/ dir xcopied by startnet.cmd) and Keyence-Enforce.ps1 (on logon, reading from the tsgwp00525 share). Each entry has an InstallerRoot-relative 'Installer' path plus standard detection. The 'Type' field is MSI, EXE, or INF: INF invokes pnputil /add-driver /install. When releasing a new VR-6000 version, update the Installer path + DetectionValue here, drop the new MSI on the tsgwp00525 share, and every Keyence PC picks it up on next logon.", + "Applications": [ + { + "_comment": "VR-6000 Series Software - main Keyence microscope/profilometer control app. Extracted from Keyence6000.exe (Inno Setup wrapper around an InstallShield 2019 MSI). Silent install works fine with /qn + REBOOT=ReallySuppress as long as you bypass the Inno wrapper - the wrapper's [Run] entry calls the bundled InstallShield Setup.exe without silent flags which hangs in session 0.", + "Name": "VR-6000 Series Software", + "Installer": "installers\\VR-6000 Series Software.msi", + "Type": "MSI", + "InstallArgs": "/qn /norestart ALLUSERS=1 REBOOT=ReallySuppress", + "DetectionMethod": "Registry", + "DetectionPath": "HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{058E7194-BDF8-4FA2-9D69-978BB0F25214}", + "DetectionName": "DisplayVersion", + "DetectionValue": "4.3.7" + }, + { + "_comment": "KEYENCE VR Series USB driver (WinUSB-based). Pulled from DriverStore after a full interactive install because dpinst.exe in the Inno wrapper needs GUI confirmation. pnputil /add-driver /install stages the INF + cat + co-installer DLLs to the Windows DriverStore; if a physical VR device is plugged in, Windows binds it immediately. Detection checks 'pnputil /enum-drivers' output for the INF filename - this matches regardless of driver version so updates (new INF with same basename) won't false-skip.", + "Name": "KEYENCE VR Series USB Driver", + "Installer": "drivers\\keyence_vr_series.inf", + "Type": "INF", + "DetectionMethod": "pnputil", + "DetectionPattern": "keyence_vr_series\\.inf" + } + ] +} diff --git a/playbook/shopfloor-setup/Keyence/lib/Install-FromManifest.ps1 b/playbook/shopfloor-setup/Keyence/lib/Install-FromManifest.ps1 new file mode 100644 index 0000000..ea3c033 --- /dev/null +++ b/playbook/shopfloor-setup/Keyence/lib/Install-FromManifest.ps1 @@ -0,0 +1,327 @@ +# Install-FromManifest.ps1 - Generic JSON-manifest installer for Keyence apps. +# +# Forked from CMM/lib/Install-FromManifest.ps1 with two additions to support +# the Keyence USB driver: +# - DetectionMethod "pnputil": matches pnputil /enum-drivers output against +# a regex (manifest field: DetectionPattern). +# - Type "INF": installs a driver package via pnputil /add-driver /install. +# +# Every Keyence manifest entry applies to Keyence PCs (no PCTypes filter; +# Keyence-Enforce.ps1 only runs on Keyence PCs by virtue of where the +# scheduled task is registered). +# +# Called from: +# - 09-Setup-Keyence.ps1 at imaging time with +# InstallerRoot= +# - Keyence-Enforce.ps1 on logon with InstallerRoot= +# +# Returns via exit code: 0 if every required app is either already installed +# or installed successfully; non-zero if any install failed. + +param( + [Parameter(Mandatory=$true)] + [string]$ManifestPath, + + [Parameter(Mandatory=$true)] + [string]$InstallerRoot, + + [Parameter(Mandatory=$true)] + [string]$LogFile +) + +$ErrorActionPreference = 'Continue' + +$logDir = Split-Path -Parent $LogFile +if (-not (Test-Path $logDir)) { + New-Item -Path $logDir -ItemType Directory -Force | Out-Null +} + +function Write-InstallLog { + param( + [Parameter(Mandatory=$true, Position=0)] + [string]$Message, + [Parameter(Position=1)] + [ValidateSet('INFO','WARN','ERROR')] + [string]$Level = 'INFO' + ) + $stamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" + $line = "[$stamp] [$Level] $Message" + Write-Host $line + + # Synchronous write-through so each line hits disk immediately, mirroring + # the preinstall runner's approach - protects forensic trail if an installer + # triggers a reboot mid-loop. + try { + $fs = New-Object System.IO.FileStream( + $LogFile, + [System.IO.FileMode]::Append, + [System.IO.FileAccess]::Write, + [System.IO.FileShare]::Read, + 4096, + [System.IO.FileOptions]::WriteThrough + ) + $bytes = [System.Text.Encoding]::UTF8.GetBytes($line + "`r`n") + $fs.Write($bytes, 0, $bytes.Length) + $fs.Flush() + $fs.Dispose() + } catch { + Add-Content -Path $LogFile -Value $line -ErrorAction SilentlyContinue + } +} + +Write-InstallLog "================================================================" +Write-InstallLog "=== Install-FromManifest session start (PID $PID) ===" +Write-InstallLog "Manifest: $ManifestPath" +Write-InstallLog "InstallerRoot: $InstallerRoot" +Write-InstallLog "================================================================" + +if (-not (Test-Path -LiteralPath $ManifestPath)) { + Write-InstallLog "Manifest not found: $ManifestPath" "ERROR" + exit 2 +} + +if (-not (Test-Path -LiteralPath $InstallerRoot)) { + Write-InstallLog "InstallerRoot not found: $InstallerRoot" "ERROR" + exit 2 +} + +try { + $config = Get-Content -LiteralPath $ManifestPath -Raw | ConvertFrom-Json +} catch { + Write-InstallLog "Failed to parse manifest: $_" "ERROR" + exit 2 +} + +if (-not $config.Applications) { + Write-InstallLog "No Applications in manifest - nothing to do" + exit 0 +} + +Write-InstallLog "Manifest lists $($config.Applications.Count) app(s)" + +# Detection helper - mirrors the preinstall runner's logic. Registry path + +# optional value name + optional exact value. The exact-value compare is how +# version-pinned drift detection works: bumping DetectionValue in the manifest +# makes the current install "fail" detection and reinstall. +function Test-AppInstalled { + param($App) + + if (-not $App.DetectionMethod) { return $false } + + try { + switch ($App.DetectionMethod) { + "Registry" { + if (-not (Test-Path $App.DetectionPath)) { return $false } + if ($App.DetectionName) { + $value = Get-ItemProperty -Path $App.DetectionPath -Name $App.DetectionName -ErrorAction SilentlyContinue + if (-not $value) { return $false } + if ($App.DetectionValue) { + return ($value.$($App.DetectionName) -eq $App.DetectionValue) + } + return $true + } + return $true + } + "File" { + return Test-Path $App.DetectionPath + } + "FileVersion" { + # Compare a file's VersionInfo.FileVersion against the + # manifest's expected value. Used for version-pinned MSI/EXE + # installs where existence alone doesn't tell you whether + # the right release is on disk. Exact string match - the + # manifest must carry the exact version the vendor stamps + # into the binary. + if (-not (Test-Path $App.DetectionPath)) { return $false } + if (-not $App.DetectionValue) { + Write-InstallLog " FileVersion detection requires DetectionValue - treating as not installed" "WARN" + return $false + } + $actual = (Get-Item $App.DetectionPath -ErrorAction Stop).VersionInfo.FileVersion + if (-not $actual) { return $false } + return ($actual -eq $App.DetectionValue) + } + "Hash" { + # Compare SHA256 of the on-disk file against the manifest's + # expected value. Used for content-versioned files that do not + # expose a DisplayVersion (secrets like eMxInfo.txt). Bumping + # DetectionValue in the manifest and replacing the file on the + # share is the entire update workflow. + if (-not (Test-Path $App.DetectionPath)) { return $false } + if (-not $App.DetectionValue) { + Write-InstallLog " Hash detection requires DetectionValue - treating as not installed" "WARN" + return $false + } + $actual = (Get-FileHash -Path $App.DetectionPath -Algorithm SHA256 -ErrorAction Stop).Hash + return ($actual -ieq $App.DetectionValue) + } + "pnputil" { + # Driver package detection via `pnputil /enum-drivers`. The + # DetectionPattern is a regex matched against the full output; + # a hit on the original INF filename (e.g. 'keyence_vr_series\.inf') + # means the package is staged in the DriverStore. + if (-not $App.DetectionPattern) { + Write-InstallLog " pnputil detection requires DetectionPattern - treating as not installed" "WARN" + return $false + } + try { + $enum = & pnputil.exe /enum-drivers 2>&1 | Out-String + return ($enum -match $App.DetectionPattern) + } catch { + Write-InstallLog " pnputil /enum-drivers failed: $_" "WARN" + return $false + } + } + default { + Write-InstallLog " Unknown detection method: $($App.DetectionMethod)" "WARN" + return $false + } + } + } catch { + Write-InstallLog " Detection check threw: $_" "WARN" + return $false + } +} + +$installed = 0 +$skipped = 0 +$failed = 0 + +foreach ($app in $config.Applications) { + # Cancel any pending reboot scheduled by a previous installer, same as the + # preinstall runner. Some Burn bundles schedule a reboot even with /norestart + # (chained bootstrapper ignores the flag for some internal prereqs). + cmd /c "shutdown /a 2>nul" *>$null + + Write-InstallLog "==> $($app.Name)" + + if (Test-AppInstalled -App $app) { + Write-InstallLog " Already installed at expected version - skipping" + $skipped++ + continue + } + + $installerPath = Join-Path $InstallerRoot $app.Installer + if (-not (Test-Path -LiteralPath $installerPath)) { + Write-InstallLog " Installer file not found: $installerPath" "ERROR" + $failed++ + continue + } + + Write-InstallLog " Installing from $installerPath" + if ($app.InstallArgs) { + Write-InstallLog " InstallArgs: $($app.InstallArgs)" + } + + try { + $psi = New-Object System.Diagnostics.ProcessStartInfo + $psi.UseShellExecute = $false + $psi.CreateNoWindow = $true + $psi.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden + + if ($app.Type -eq "MSI") { + $safeName = $app.Name -replace '[^a-zA-Z0-9]','_' + $msiLog = Join-Path $logDir "msi-$safeName.log" + if (Test-Path $msiLog) { Remove-Item $msiLog -Force -ErrorAction SilentlyContinue } + + $psi.FileName = "msiexec.exe" + $psi.Arguments = "/i `"$installerPath`"" + if ($app.InstallArgs) { $psi.Arguments += " " + $app.InstallArgs } + $psi.Arguments += " /L*v `"$msiLog`"" + Write-InstallLog " msiexec verbose log: $msiLog" + } + elseif ($app.Type -eq "EXE") { + $psi.FileName = $installerPath + if ($app.InstallArgs) { $psi.Arguments = $app.InstallArgs } + if ($app.LogFile) { + Write-InstallLog " Installer log: $($app.LogFile)" + } + } + elseif ($app.Type -eq "INF") { + # Driver package: stage to Windows DriverStore via pnputil. The + # /install flag binds the driver to any matching hardware currently + # present; drivers without a bound device still persist in the + # store and attach when hardware is plugged in later. + $psi.FileName = "pnputil.exe" + $psi.Arguments = "/add-driver `"$installerPath`" /install" + } + else { + Write-InstallLog " Unsupported Type: $($app.Type) - skipping" "ERROR" + $failed++ + continue + } + + # Use Process.Start directly rather than Start-Process because PS 5.1's + # Start-Process -PassThru disposes the process handle when control returns, + # making ExitCode read as $null. Direct Process.Start gives us a live handle. + $proc = [System.Diagnostics.Process]::Start($psi) + + # No per-app timeout here - PC-DMIS bundles can run 20+ minutes on slow + # disks and we don't want to kill them mid-chain. The calling script + # controls overall session timing. + $proc.WaitForExit() + $exitCode = $proc.ExitCode + + # Burn and MSI exit codes: + # 0 success + # 1641 success, reboot initiated + # 3010 success, reboot pending + if ($exitCode -eq 0 -or $exitCode -eq 1641 -or $exitCode -eq 3010) { + Write-InstallLog " Exit code $exitCode - SUCCESS" + if ($exitCode -eq 3010) { Write-InstallLog " (Reboot pending for $($app.Name))" } + if ($exitCode -eq 1641) { Write-InstallLog " (Installer initiated a reboot for $($app.Name))" } + $installed++ + } + else { + Write-InstallLog " Exit code $exitCode - FAILED" "ERROR" + + if ($app.Type -eq "EXE" -and $app.LogFile -and (Test-Path $app.LogFile)) { + Write-InstallLog " --- last 30 lines of $($app.LogFile) ---" + Get-Content $app.LogFile -Tail 30 -ErrorAction SilentlyContinue | ForEach-Object { + Write-InstallLog " $_" + } + Write-InstallLog " --- end installer log tail ---" + } + + if ($app.Type -eq "MSI" -and $msiLog -and (Test-Path $msiLog)) { + Write-InstallLog " --- meaningful lines from $msiLog ---" + $patterns = @( + 'Note: 1: ', + 'return value 3', + 'Error \d+\.', + 'CustomAction .* returned actual error', + 'Failed to ', + 'Installation failed', + '1: 2262', + '1: 2203', + '1: 2330' + ) + $regex = ($patterns -join '|') + $matches = Select-String -Path $msiLog -Pattern $regex -ErrorAction SilentlyContinue | + Select-Object -First 30 + if ($matches) { + foreach ($m in $matches) { Write-InstallLog " $($m.Line.Trim())" } + } else { + Get-Content $msiLog -Tail 25 -ErrorAction SilentlyContinue | ForEach-Object { + Write-InstallLog " $_" + } + } + Write-InstallLog " --- end MSI log scan ---" + } + + $failed++ + } + } catch { + Write-InstallLog " Install threw: $_" "ERROR" + $failed++ + } +} + +Write-InstallLog "============================================" +Write-InstallLog "Install-FromManifest complete: $installed installed, $skipped skipped, $failed failed" +Write-InstallLog "============================================" + +cmd /c "shutdown /a 2>nul" *>$null + +if ($failed -gt 0) { exit 1 } +exit 0 diff --git a/playbook/shopfloor-setup/site-config.json b/playbook/shopfloor-setup/site-config.json index c3acae4..e011e81 100644 --- a/playbook/shopfloor-setup/site-config.json +++ b/playbook/shopfloor-setup/site-config.json @@ -153,7 +153,8 @@ }, "Keyence": { - "_comment": "TODO: add Keyence-specific apps when details are known", + "_comment": "Keyence VR-6000 microscope/profilometer PCs. At imaging time, 09-Setup-Keyence.ps1 installs VR-6000 Series Software MSI + KEYENCE VR USB driver from the WinPE-staged shopfloor-setup\\Keyence\\ bundle. Post-imaging, the 'GE Keyence Enforce' scheduled task runs Keyence-Enforce.ps1 on user logon and enforces versions against the tsgwp00525 share below (SFLD creds provisioned by Azure DSC unlock the mount). keyenceSharePath is the ongoing-enforcement source; bump the manifest + MSI on the share to push updates fleet-wide.", + "keyenceSharePath": "\\\\tsgwp00525.wjs.geaerospace.net\\shared\\dt\\shopfloor\\keyence\\machineapps", "startupItems": [ { "label": "WJ Shopfloor", "type": "existing", "sourceLnk": "WJ Shopfloor.lnk" } ],