# .SYNOPSIS Prints every .zpl label that lands in your Downloads folder, then moves it to Downloads\zpl-sts-printed. With this running, the portal's "Download .zpl" button is a print button. .DESCRIPTION A web page cannot send anything to a printer, and should not be able to. So the portal saves the label as a file, the way every browser allows, and this script does the one thing a page cannot: it opens a connection to the printer on port 9100 and writes the file to it, byte for byte. WHAT IT DOES, AND ALL IT DOES - Every 2 seconds, looks in your Downloads folder for files ending .zpl. - Opens each one only once the browser has finished writing it. - Prints it ONLY if it is a complete Zebra label: it contains ^XA and ^XZ and is under 64 KB. Anything else is moved to Downloads\zpl-sts-not-printed, with the reason in the log. - Sends it to the printer named in the ZPL_PRINTER setting, port 9100. - Moves it to Downloads\zpl-sts-printed with the date and time in front of the name, and writes one line to Downloads\zpl-sts-printed\print-log.txt. - Never sends a file twice: a send that fails moves the file to Downloads\zpl-sts-not-printed rather than trying again, because a half-sent label that is re-sent prints twice. WHAT IT NEVER DOES - It does not read, move or delete any file that does not end in .zpl. - It does not connect to anything except the printer's address on port 9100. Nothing is sent anywhere else, ever. - It does not change any setting on the PC. The install copies this file to %LOCALAPPDATA%\StocktakesOnline and puts a shortcut in your Startup folder; uninstall removes both. Written 13-11-2026 for Stocktakes Online / ScanTrack Systems. It is kept short on purpose, so that anyone can read all of it before running it. .PARAMETER Install Copies this script to %LOCALAPPDATA%\StocktakesOnline, asks for the printer address if ZPL_PRINTER is not set, puts a shortcut in Startup so it runs when you sign in to Windows, and starts it now. .PARAMETER Uninstall Stops it, removes the Startup shortcut and the copy. ZPL_PRINTER and the zpl-sts-printed folder are left alone. .PARAMETER Status Says whether it is installed, whether it is running, and which printer and folder it uses. .PARAMETER Printer The printer's IP address. Defaults to the ZPL_PRINTER setting. .EXAMPLE .\print-zpl-watcher.ps1 -Install (or double-click print-zpl-watcher.cmd, which does the same) .EXAMPLE .\print-zpl-watcher.ps1 # run it in this window, to watch it work #> param( [switch]$Install, [switch]$Uninstall, [switch]$Status, [string]$Printer = $(if ($env:ZPL_PRINTER) { $env:ZPL_PRINTER } else { [Environment]::GetEnvironmentVariable('ZPL_PRINTER', 'User') }), [int]$Port = 9100 ) $ErrorActionPreference = 'Stop' $AppDir = Join-Path $env:LOCALAPPDATA 'StocktakesOnline' $Installed = Join-Path $AppDir 'print-zpl-watcher.ps1' $Shortcut = Join-Path ([Environment]::GetFolderPath('Startup')) 'Print ZPL labels (Stocktakes Online).lnk' $MaxBytes = 64 * 1024 function Get-DownloadsFolder { # The browser's Downloads folder, even if it has been moved from the default. try { $p = (New-Object -ComObject Shell.Application).NameSpace('shell:Downloads').Self.Path if ($p -and (Test-Path -LiteralPath $p)) { return $p } } catch { } return Join-Path ([Environment]::GetFolderPath('UserProfile')) 'Downloads' } function Get-RunningWatchers { # Other copies of this script, by their command line. Never this process. Get-CimInstance Win32_Process -Filter "Name = 'powershell.exe'" | Where-Object { $_.CommandLine -like '*print-zpl-watcher.ps1*' -and $_.ProcessId -ne $PID } } function Write-Log([string]$Dir, [string]$Line) { $stamp = Get-Date -Format 'dd-MM-yyyy HH:mm:ss' Add-Content -LiteralPath (Join-Path $Dir 'print-log.txt') -Value "$stamp $Line" -Encoding UTF8 Write-Host "$stamp $Line" } function Send-Bytes([byte[]]$Bytes, [string]$Address, [int]$ToPort) { $client = New-Object System.Net.Sockets.TcpClient try { $connect = $client.BeginConnect($Address, $ToPort, $null, $null) if (-not $connect.AsyncWaitHandle.WaitOne(5000, $false)) { throw "no answer from ${Address}:${ToPort} in 5 seconds - is the printer on, and on this network?" } $client.EndConnect($connect) $stream = $client.GetStream() $stream.Write($Bytes, 0, $Bytes.Length) $stream.Flush() } finally { if ($client.Connected) { $client.Close() } $client.Dispose() } } # ---------------------------------------------------------------- install if ($Install) { if ([string]::IsNullOrWhiteSpace($Printer)) { $Printer = Read-Host "Printer's IP address (for example 192.168.1.81)" if ([string]::IsNullOrWhiteSpace($Printer)) { Write-Host 'No address - nothing installed.' -ForegroundColor Red; exit 1 } } $Printer = $Printer.Trim() # Saved for the account (so the Startup copy finds it after a reboot) and # set in this process (so the copy started right now inherits it). [Environment]::SetEnvironmentVariable('ZPL_PRINTER', $Printer, 'User') $env:ZPL_PRINTER = $Printer Write-Host "ZPL_PRINTER is $Printer for your Windows account." New-Item -ItemType Directory -Force -Path $AppDir | Out-Null Copy-Item -LiteralPath $PSCommandPath -Destination $Installed -Force $args = "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$Installed`"" $shell = New-Object -ComObject WScript.Shell $lnk = $shell.CreateShortcut($Shortcut) $lnk.TargetPath = 'powershell.exe' $lnk.Arguments = $args $lnk.WorkingDirectory = $AppDir $lnk.WindowStyle = 7 $lnk.Description = 'Prints .zpl labels that land in Downloads (Stocktakes Online)' $lnk.Save() Get-RunningWatchers | ForEach-Object { Stop-Process -Id $_.ProcessId -Force } Start-Process powershell.exe -ArgumentList $args -WindowStyle Hidden Write-Host 'Installed and running.' -ForegroundColor Green Write-Host " Watching: $(Get-DownloadsFolder)" Write-Host " Printer: ${Printer}:${Port}" Write-Host " Starts with Windows from: $Shortcut" Write-Host " To remove: print-zpl-watcher.cmd uninstall" exit 0 } # -------------------------------------------------------------- uninstall if ($Uninstall) { $n = 0 Get-RunningWatchers | ForEach-Object { Stop-Process -Id $_.ProcessId -Force; $n++ } if (Test-Path -LiteralPath $Shortcut) { Remove-Item -LiteralPath $Shortcut -Force } if (Test-Path -LiteralPath $Installed) { Remove-Item -LiteralPath $Installed -Force } Write-Host "Removed. Stopped $n running copy(ies); the Startup shortcut and the installed copy are gone." -ForegroundColor Green Write-Host 'ZPL_PRINTER and the Downloads\zpl-sts-printed folder are left as they were.' exit 0 } # ----------------------------------------------------------------- status if ($Status) { $running = @(Get-RunningWatchers).Count Write-Host "Installed copy: $(if (Test-Path -LiteralPath $Installed) { $Installed } else { 'no' })" Write-Host "Startup shortcut: $(if (Test-Path -LiteralPath $Shortcut) { 'yes' } else { 'no' })" Write-Host "Running now: $(if ($running) { "yes ($running)" } else { 'no' })" Write-Host "Printer: $(if ($Printer) { "${Printer}:${Port}" } else { 'NOT SET - run the install, or setx ZPL_PRINTER
' })" Write-Host "Watching: $(Get-DownloadsFolder)" exit 0 } # ------------------------------------------------------------------ watch if ([string]::IsNullOrWhiteSpace($Printer)) { Write-Host 'No printer address. Run the install, or: setx ZPL_PRINTER 192.168.1.81' -ForegroundColor Red exit 1 } # One copy at a time. A second one would race the first for every file. $mutex = New-Object System.Threading.Mutex($false, 'Local\StocktakesOnline.PrintZplWatcher') if (-not $mutex.WaitOne(0, $false)) { Write-Host 'Already running.'; exit 0 } $Downloads = Get-DownloadsFolder $PrintedDir = Join-Path $Downloads 'zpl-sts-printed' $RefusedDir = Join-Path $Downloads 'zpl-sts-not-printed' New-Item -ItemType Directory -Force -Path $PrintedDir | Out-Null # Only files that arrive from now on. On its first run on Andrei's PC # (13-11-2026) it printed two labels that had been sitting in Downloads for # two days - nobody asked for those. Whatever is already there stays there. $StartedAt = Get-Date $already = @(Get-ChildItem -LiteralPath $Downloads -Filter '*.zpl' -File -ErrorAction SilentlyContinue).Count Write-Log $PrintedDir "watching $Downloads for .zpl files, printing to ${Printer}:${Port}$(if ($already) { " (leaving $already already there alone)" })" while ($true) { $files = @(Get-ChildItem -LiteralPath $Downloads -Filter '*.zpl' -File -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -ge $StartedAt }) foreach ($f in $files) { # Is the browser finished with it? Opening it with no sharing fails # while a download is still being written; try again next round. try { $fs = [System.IO.File]::Open($f.FullName, 'Open', 'Read', 'None') $fs.Close() } catch { continue } $stamp = Get-Date -Format 'yyyy-MM-dd HHmmss' $reason = $null $bytes = $null try { if ($f.Length -gt $MaxBytes) { throw "too big to be a label ($($f.Length) bytes)" } $bytes = [System.IO.File]::ReadAllBytes($f.FullName) $text = [System.Text.Encoding]::ASCII.GetString($bytes) if ($text -notmatch '\^XA' -or $text -notmatch '\^XZ') { throw 'not a label (no ^XA ... ^XZ)' } } catch { $reason = $_.Exception.Message } if (-not $reason) { try { Send-Bytes $bytes $Printer $Port } catch { $reason = "not sent: $($_.Exception.Message)" } } if ($reason) { New-Item -ItemType Directory -Force -Path $RefusedDir | Out-Null $dest = Join-Path $RefusedDir "$stamp $($f.Name)" Move-Item -LiteralPath $f.FullName -Destination $dest -Force Write-Log $PrintedDir "REFUSED $($f.Name) - $reason - moved to zpl-sts-not-printed" } else { $dest = Join-Path $PrintedDir "$stamp $($f.Name)" Move-Item -LiteralPath $f.FullName -Destination $dest -Force Write-Log $PrintedDir "printed $($f.Name) ($($bytes.Length) bytes) to ${Printer}:${Port}" } } Start-Sleep -Seconds 2 }