Most print automation stops at submitting a job and hopes for the best. This lesson shows you how to build a complete, unattended print management workflow in Power Automate Desktop — including printer validation, job submission, WMI-based queue monitoring, stuck-job recovery, and structured logging — so your bot knows not just that it printed, but that printing actually succeeded.

Picture this: your operations team prints 200 shipping labels every morning from a legacy warehouse management system. The process requires a human to log in, navigate to the reports module, select the correct network printer, adjust print settings, and babysit the queue until every label clears. If the print job stalls, somebody has to notice, cancel the stuck job, and resubmit. The whole ritual takes 45 minutes of a person's morning — every single morning.
Print automation sounds mundane until you calculate the time it consumes and the errors it introduces. Misselected printers mean reprints. Unchecked stuck queues mean delayed shipments. When you're running unattended bots that generate documents, invoices, or reports at scale, print management becomes genuinely critical infrastructure. Power Automate Desktop gives you multiple approaches to tackle this: built-in printer actions, PowerShell integration for queue monitoring, and hybrid strategies that combine both. Getting this right means your unattended flow not only submits print jobs reliably but also verifies they completed before moving on.
By the end of this lesson, you'll be able to build a production-ready, unattended print automation workflow that selects the correct printer, submits documents programmatically, monitors the print queue for completion or failure, handles stuck jobs, and logs the outcome — without anyone touching the machine.
What you'll learn:
You should be comfortable building desktop flows in Power Automate Desktop and working with variables, conditions, and loops. If you haven't set up PAD or created your first flow yet, start with Getting Started with Power Automate Desktop: Installing, Recording, and Running Your First Desktop Flow. You should also understand how unattended runs differ from attended ones — if that distinction is fuzzy, read Attended vs Unattended RPA: Choosing a Run Mode and Configuring Machines in Power Automate first. Basic familiarity with PowerShell is helpful but not required; every script in this lesson is fully explained.
Before writing a single action, you need an honest picture of PAD's native printing capabilities so you know when to reach for a script.
PAD's native print actions are genuinely useful for straightforward scenarios:
PrintTo verb. Works well for PDFs, Word documents, Excel files, and any file type with a registered print association.The limitation is what comes after submission. PAD has no built-in action to query queue status, check whether a job completed, or cancel a stuck job. That gap is where PowerShell earns its keep. Windows Management Instrumentation (WMI) exposes the entire print subsystem through the Win32_PrintJob and Win32_Printer classes, and you can query them in a few lines of PowerShell from inside any desktop flow.
The practical strategy for robust print automation is therefore:
This layered approach is exactly the same principle you'd use for scripting inside desktop flows when built-in actions run out of steam.
Printer management logic belongs in a dedicated subflow, not scattered through your main automation. If your main flow generates a report, extracts data from a system, and then prints, cramming all three concerns into one monolithic sequence makes debugging miserable. Structure it like this:
Main Flow
ValidatePrinterSubmitPrintJobMonitorPrintQueueHandlePrintResultThis modular design means you can reuse SubmitPrintJob and MonitorPrintQueue across different automations without reimplementing them. For a deeper dive into this pattern, see Subflows and Reusable Logic in Power Automate Desktop.
Create the following input variables for your main flow. These will pass down to subflows:
| Variable | Type | Example Value |
|---|---|---|
PrinterName |
Text | \\PRINT-SRV01\WH-LabelPrinter |
DocumentPath |
Text | C:\Reports\ShippingLabels_2024-01-15.pdf |
NumberOfCopies |
Number | 1 |
MaxWaitSeconds |
Number | 120 |
JobOwnerFilter |
Text | SVC_RPA_Account |
Note
In unattended runs, the Windows session runs under a service account. Your JobOwnerFilter should match that account name exactly so your queue monitoring only watches jobs submitted by this bot, not jobs from other users sharing the printer.
Before submitting anything, your flow should confirm that the target printer actually exists and is online. Submitting a job to an offline or nonexistent printer produces an error that's annoying to diagnose if you don't check upfront.
Add a Run PowerShell script action with this script. Set the output to a variable called PrinterListRaw:
# Retrieve all printers visible to this session
$printers = Get-Printer | Select-Object Name, PrinterStatus, DriverName |
ForEach-Object {
"$($_.Name)|$($_.PrinterStatus)|$($_.DriverName)"
}
$printers -join "`n"
The output will be a newline-delimited string of pipe-separated values, one printer per line. Something like:
Microsoft Print to PDF|0|Microsoft Print To PDF
\\PRINT-SRV01\WH-LabelPrinter|0|Zebra ZPL Label Printer
\\PRINT-SRV01\Office-HP-CLJ|0|HP Color LaserJet
\\PRINT-SRV01\Archive-Lexmark|6|Lexmark Universal v2
A PrinterStatus of 0 means idle/ready. A value of 6 or higher typically indicates an error or offline state.
Now parse that output into something usable. Use a Split text action on PrinterListRaw with delimiter \n to get a list variable PrinterLines. Then loop through PrinterLines with a For each loop, splitting each line on | to extract name and status.
Here's the validation logic inside the loop:
# Pseudocode representing your PAD actions:
For Each CurrentLine in PrinterLines:
Split CurrentLine by '|' → LineParts
If LineParts[0] = PrinterName Then
Set PrinterFound = True
Set PrinterStatus = LineParts[1]
If PrinterStatus ≠ '0' Then
Set PrinterReady = False
# Log warning: printer found but not in ready state
Else
Set PrinterReady = True
End If
Break
End If
End For
After the loop:
PrinterFound is False, throw a handled error with a meaningful message and stop the flow.PrinterFound is True but PrinterReady is False, you have a decision: abort or proceed anyway (some printers report non-zero status briefly during initialization).Warning
Network printers on a print server can appear in Get-Printer output but still be offline from the perspective of the print spooler if the server connection is intermittent. The most reliable check combines Get-Printer status with a direct WMI query — we'll do exactly this in the queue monitoring section.
PAD's native Set default printer action takes a printer name string and updates HKCU\Software\Microsoft\Windows NT\CurrentVersion\Windows\Device under the hood. This is session-scoped, which means it only affects the current Windows session — perfect for unattended runs where each bot session is isolated.
Add a Set default printer action:
%PrinterName%Then immediately verify with Get default printer and confirm the returned value matches your input:
Get default printer → CurrentDefault
If CurrentDefault ≠ PrinterName Then
# The set operation failed silently — treat as error
Throw custom error: "Failed to set default printer to %PrinterName%"
End If
Tip
If you're printing to an application that ignores the Windows default printer and maintains its own last-used printer setting (SAP GUI and many legacy line-of-business apps do this), setting the Windows default isn't enough. In those cases you'll need to interact directly with the application's print dialog — which is a UI automation problem. The techniques in Automating Legacy Windows Applications with UI Automation in Power Automate Desktop apply directly here.
For PDF files, Word documents, Excel workbooks, and other shell-printable file types, PAD's Print document action is the cleanest option. It invokes the file's registered PrintTo shell verb with the target printer name.
Configure the action:
%DocumentPath%%PrinterName%This is functionally equivalent to right-clicking the file in Windows Explorer and choosing "Print." The action returns quickly — it submits the job to the spooler, it does not wait for the job to complete. That's the job of your monitoring subflow.
For scenarios where the Print Document action doesn't work (unusual file types, network path quirks, or when you need to specify copies programmatically), PowerShell gives you finer control:
param(
[string]$DocPath,
[string]$Printer,
[int]$Copies = 1
)
# Use the shell to print with PrintTo verb
$shell = New-Object -ComObject Shell.Application
$folder = $shell.Namespace([System.IO.Path]::GetDirectoryName($DocPath))
$file = $folder.ParseName([System.IO.Path]::GetFileName($DocPath))
# For PDFs specifically, use Acrobat Reader CLI if installed
# This gives you copies control without UI interaction
$adobePath = "C:\Program Files\Adobe\Acrobat DC\Acrobat\Acrobat.exe"
if (Test-Path $adobePath) {
$args = "/N /T `"$DocPath`" `"$Printer`""
Start-Process -FilePath $adobePath -ArgumentList $args -WindowStyle Hidden
} else {
# Fallback to shell PrintTo verb
Start-Process -FilePath $DocPath -Verb PrintTo -ArgumentList "`"$Printer`"" -WindowStyle Hidden
}
Write-Output "Job submitted at $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
Pass %DocumentPath%, %PrinterName%, and %NumberOfCopies% as script parameters using PAD's Script parameters field in the Run PowerShell script action.
Note
The Adobe Acrobat Reader command-line printing approach (/T) is reliable for PDFs but requires Acrobat Reader or Acrobat DC to be installed. For pure PDF printing without Adobe, consider SumatraPDF which has excellent command-line support: SumatraPDF.exe -print-to "PrinterName" -print-settings "1x" document.pdf. The -print-settings "1x" controls copies.
Sometimes your bot generates output directly inside an application — a report from a Windows desktop app, for example — and you need to trigger that application's built-in print function. This is a UI automation scenario: use keyboard shortcuts (typically Ctrl+P to open the print dialog), handle the dialog, select the printer from a dropdown, and confirm. The techniques for navigating these dialogs reliably are covered in Automating Windows Dialog Boxes and Pop-Up Windows in Power Automate Desktop.
For the in-application approach, your flow structure looks like:
# After navigating to the report in the application:
Send keys: Ctrl+P # Opens print dialog
Wait for window: "Print" # Wait for dialog to appear
# Select printer from combo box using UI automation
# Set copies if needed
# Click OK/Print button
# Wait for dialog to close
The print dialog itself is a standard Windows dialog, so its UI elements are generally selectable without heroic selector tricks.
This is where most print automation falls apart. Submitting a job is easy. Knowing whether it completed is the hard part.
The Win32_PrintJob WMI class tracks jobs in the Windows print spooler. Key properties:
| Property | Meaning |
|---|---|
Name |
Printer name + job ID, e.g., \\PRINT-SRV01\WH-LabelPrinter,42 |
Document |
Document name as it appears in the queue |
JobId |
Unique integer ID for this job in the queue |
Owner |
Windows account that submitted the job |
StatusMask |
Bitmask representing current job state |
Status |
Human-readable status string |
TotalPages |
Total pages in the job |
PagesPrinted |
Pages printed so far |
Size |
Job size in bytes |
The StatusMask values to care about:
| Bitmask Value | Status Meaning |
|---|---|
| 0 | Queued / being processed |
| 1 | Paused |
| 2 | Error |
| 4 | Deleting |
| 16 | Printing |
| 32 | Offline |
| 48 | Paper out |
| 2048 | Printed (completed successfully) |
A job that disappears from the queue entirely has usually printed successfully — Windows removes completed jobs quickly unless you've configured the spooler to retain them.
Here's the PowerShell script for your monitoring subflow. It polls the queue every few seconds, looking for your job:
param(
[string]$TargetPrinter,
[string]$JobOwner,
[int]$MaxWaitSeconds = 120,
[string]$DocumentName = ""
)
$startTime = Get-Date
$pollIntervalSeconds = 5
$jobFound = $false
$jobCompleted = $false
$jobError = $false
$finalStatus = "UNKNOWN"
$jobId = -1
while ((New-TimeSpan -Start $startTime -End (Get-Date)).TotalSeconds -lt $MaxWaitSeconds) {
# Query WMI for print jobs on target printer from our owner
$jobs = Get-WmiObject -Class Win32_PrintJob |
Where-Object {
$_.Name -like "$TargetPrinter*" -and
$_.Owner -like "*$JobOwner*"
}
if ($jobs) {
foreach ($job in $jobs) {
$jobFound = $true
$jobId = $job.JobId
$statusMask = $job.StatusMask
$pagesTotal = $job.TotalPages
$pagesDone = $job.PagesPrinted
# Check for error states
if ($statusMask -band 2) {
$jobError = $true
$finalStatus = "ERROR"
break
}
# Check for paused (might indicate paper out or similar)
if ($statusMask -band 1) {
$finalStatus = "PAUSED"
}
# Job actively printing
if ($statusMask -band 16) {
$finalStatus = "PRINTING|$pagesDone/$pagesTotal"
}
}
if ($jobError) { break }
} else {
# No matching jobs in queue
if ($jobFound) {
# We saw the job before, now it's gone — that means it completed
$jobCompleted = $true
$finalStatus = "COMPLETED"
break
} else {
# Haven't found it yet — might still be spooling
$finalStatus = "SPOOLING"
}
}
Start-Sleep -Seconds $pollIntervalSeconds
}
if (-not $jobCompleted -and -not $jobError) {
if (-not $jobFound) {
$finalStatus = "JOB_NOT_FOUND"
} else {
$finalStatus = "TIMEOUT"
}
}
# Output structured result for PAD to parse
Write-Output "$finalStatus|$jobId"
In PAD, capture the output of this script into a variable QueueMonitorResult, then split on | to get MonitorStatus and MonitorJobId.
Your decision tree after monitoring:
If MonitorStatus = 'COMPLETED' Then
Log success, continue flow
Else If MonitorStatus = 'ERROR' Then
Call subflow: CancelAndResubmit
Else If MonitorStatus = 'TIMEOUT' Then
Call subflow: EscalateToOperator
Else If MonitorStatus = 'JOB_NOT_FOUND' Then
# Either job completed before first poll, or submission failed
# Check application output or resubmit with longer pre-poll delay
Call subflow: VerifyOutputExists
End If
Key insight
Jobs can disappear from the WMI query almost immediately after printing finishes because Windows removes them from the spooler. If your polling interval is 5 seconds and the job prints in 2 seconds, you'll see JOB_NOT_FOUND on the very first poll. That's often success, not failure. The $jobFound flag in the script above handles this — if the job was never seen, that's different from a job that appeared and then disappeared.
Stuck jobs are the bane of print automation. A job stalls because a printer goes offline mid-print, runs out of paper, or simply hangs in the spooler. If your monitoring loop detects an error or the job has been PAUSED for longer than a threshold, you need to cancel it and decide whether to resubmit.
Here's the PowerShell for cancelling a specific job by ID, and clearing all error jobs from a printer:
param(
[string]$TargetPrinter,
[int]$JobId = -1,
[switch]$ClearAllErrors
)
if ($JobId -gt 0) {
# Cancel specific job
$job = Get-WmiObject -Class Win32_PrintJob |
Where-Object { $_.Name -like "$TargetPrinter*" -and $_.JobId -eq $JobId }
if ($job) {
$result = $job.Delete()
if ($result.ReturnValue -eq 0) {
Write-Output "CANCELLED|$JobId"
} else {
Write-Output "CANCEL_FAILED|$JobId|$($result.ReturnValue)"
}
} else {
Write-Output "JOB_NOT_FOUND|$JobId"
}
}
if ($ClearAllErrors) {
# Find and cancel all error/paused jobs on this printer
$errorJobs = Get-WmiObject -Class Win32_PrintJob |
Where-Object {
$_.Name -like "$TargetPrinter*" -and
(($_.StatusMask -band 2) -or ($_.StatusMask -band 1))
}
$cancelledCount = 0
foreach ($job in $errorJobs) {
$job.Delete() | Out-Null
$cancelledCount++
}
Write-Output "CLEARED|$cancelledCount"
}
Warning
Calling Delete() on a Win32_PrintJob via WMI requires that your flow's service account has sufficient privileges on the print server. Standard user accounts can only delete their own jobs. If the unattended bot runs as a service account with limited privileges, you may need to run the cancellation script elevated, or grant the service account Manage Documents permission on the printer. Test this during development, not at 2 AM when a production queue is jammed.
After cancelling, implement a retry counter. Don't resubmit indefinitely:
Set RetryCount = 0
Set MaxRetries = 3
While RetryCount < MaxRetries:
Call subflow: SubmitPrintJob
Call subflow: MonitorPrintQueue
If MonitorStatus = 'COMPLETED' Then
Break
Else
Cancel stuck job (PowerShell)
Wait 10 seconds
Increment RetryCount
End If
End While
If RetryCount = MaxRetries And MonitorStatus ≠ 'COMPLETED' Then
# Escalate — email alert, Teams notification, log to database
Call subflow: EscalateFailure
End If
This retry pattern should feel familiar from Error Handling in Desktop Flows: On Block Error, Retry Policies, and Recovery Screenshots. The difference here is that printer errors often recover on their own (the paper out condition gets fixed by a human), so a 30-60 second wait between retries is worthwhile before concluding the printer is truly unavailable.
Occasionally the Windows Print Spooler service (Spooler) gets stuck, and no amount of job cancellation fixes it. In that case, the nuclear option is restarting the spooler service. This should be a last resort because it clears all print jobs from all printers on the machine.
# Check spooler health
$spooler = Get-Service -Name Spooler
Write-Output $spooler.Status
# Restart if needed (requires admin privileges)
if ($spooler.Status -ne 'Running') {
Restart-Service -Name Spooler -Force
Start-Sleep -Seconds 5
$spooler.Refresh()
Write-Output "RESTARTED|$($spooler.Status)"
} else {
Write-Output "RUNNING|OK"
}
Combining this with Windows service monitoring techniques from Automating Windows Service and Process Management in Power Automate Desktop gives you a complete health-check routine you can run at the start of your print automation to ensure the environment is ready before you submit anything.
In an unattended, production context, logging isn't optional. Every print job attempt — successful or not — should produce a structured log entry. This serves two purposes: operational visibility and debugging when something goes wrong at 3 AM and you need to reconstruct what happened.
A simple but effective approach: write a log entry to a CSV file after each job attempt.
param(
[string]$PrinterName,
[string]$DocumentPath,
[string]$Status,
[string]$JobId,
[string]$ErrorDetail = "",
[string]$LogFilePath = "C:\RPA_Logs\PrintLog.csv"
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$documentName = [System.IO.Path]::GetFileName($DocumentPath)
$logLine = "`"$timestamp`",`"$PrinterName`",`"$documentName`",`"$Status`",`"$JobId`",`"$ErrorDetail`""
# Create log file with header if it doesn't exist
if (-not (Test-Path $LogFilePath)) {
$header = '"Timestamp","Printer","Document","Status","JobId","ErrorDetail"'
Set-Content -Path $LogFilePath -Value $header -Encoding UTF8
}
Add-Content -Path $LogFilePath -Value $logLine -Encoding UTF8
Write-Output "Logged: $Status"
Tip
If your environment uses a centralized logging database rather than flat files, adapt this to write via Invoke-SqlCmd instead of Add-Content. The database automation patterns in PAD work well for this — a simple INSERT into a print_audit table gives you queryable history that operations teams can use to track SLAs.
For report-style visibility, pair this with the report generation and distribution automation pattern to automatically email a daily print job summary to your operations supervisor every morning.
Let's put everything together into a realistic scenario: an unattended bot that runs every weekday at 6:00 AM, reads a list of pending shipments from a CSV, prints the corresponding label PDF for each one, confirms completion, and logs the outcome.
Create these flow input variables:
LabelFolderPath = C:\ShippingLabels\Pending\PrinterName = \\PRINT-SRV01\WH-LabelPrinterLogFilePath = C:\RPA_Logs\LabelPrintLog.csvMaxWaitPerJob = 60 (seconds)Use PAD's Get files in folder action on %LabelFolderPath% with filter *.pdf. Store results in LabelFiles list.
Add a check: if LabelFiles is empty, log "No labels pending" and exit gracefully.
Add a Run PowerShell script action with the printer validation script from earlier. If validation fails, log the error and exit.
For Each LabelFile in LabelFiles:
Set CurrentDocument = LabelFile.FullName
Set CurrentDocumentName = LabelFile.NameWithoutExtension
# Submit job
Print document: CurrentDocument to PrinterName
# Short wait to let job enter spooler
Wait 3 seconds
# Monitor queue
Run PowerShell: MonitorScript with params PrinterName, JobOwner, MaxWaitPerJob
Parse result → MonitorStatus, MonitorJobId
If MonitorStatus = 'COMPLETED' or MonitorStatus = 'JOB_NOT_FOUND' Then
Run PowerShell: LogScript with Status='SUCCESS'
# Move file to processed folder
Move file: CurrentDocument to C:\ShippingLabels\Printed\
Else If MonitorStatus = 'ERROR' Then
Run PowerShell: CancelScript with JobId=MonitorJobId
Run PowerShell: LogScript with Status='ERROR', ErrorDetail=MonitorStatus
# Move to failed folder for human review
Move file: CurrentDocument to C:\ShippingLabels\Failed\
Else If MonitorStatus = 'TIMEOUT' Then
Run PowerShell: LogScript with Status='TIMEOUT'
# Leave file in place for retry next run
End If
# Brief pause between jobs to avoid overwhelming the queue
Wait 2 seconds
End For
After the loop, run a PowerShell script that reads the log file, counts successes/failures for today, and outputs a summary string. Display this in a final log entry or use it to trigger a cloud flow notification back to a Teams channel.
Configure this flow for unattended execution via Power Automate cloud, scheduled at 06:00 AM weekdays. Ensure your machine is registered and the service account has the correct printer permissions. For machine configuration, see Managing Machines and Machine Groups for Scalable Unattended Automation in Power Automate.
The most common gotcha. Network printers installed for a user account aren't visible in a different session. When PAD runs unattended under a service account, the service account must have the network printer explicitly mapped to it. Connect as the service account (or use Run as different user via Remote Desktop), navigate to the print server, and install the printer driver for that account. Alternatively, use a Group Policy to map shared printers to all users, or push the connection with a PowerShell script run as the service account:
Add-Printer -ConnectionName "\\PRINT-SRV01\WH-LabelPrinter"
WMI sometimes uses the NetBIOS printer name rather than the UNC path. If your TargetPrinter variable is \\PRINT-SRV01\WH-LabelPrinter but WMI stores it as WH-LabelPrinter, the -like filter won't match. Debug this by running Get-WmiObject -Class Win32_PrintJob | Select-Object Name, Owner, Status directly in a PowerShell session under the service account and inspecting the Name field format.
This happens when the application being printed from caches its own printer selection. The Windows default printer change happens at the registry level, but some apps read their own preferences. If you're printing through an application rather than directly from a file, you need to interact with the application's print dialog to select the printer explicitly.
If MonitorStatus immediately returns JOB_NOT_FOUND or COMPLETED but nothing actually printed, the job entered the spooler and was rejected silently. Causes include: no compatible driver, the document format is incompatible with the printer, or the printer's driver settings reject the job. Enable spooler event logging (Event Viewer > Windows Logs > Application, filter by source Print) to see the actual rejection reason.
Unattended sessions sometimes inherit a restrictive PowerShell execution policy. Test by running your script manually under the service account. If blocked, set the policy at the machine level (requires admin): Set-ExecutionPolicy -Scope LocalMachine -ExecutionPolicy RemoteSigned. Alternatively, use PAD's script action with the -ExecutionPolicy Bypass parameter: add -ExecutionPolicy Bypass -File "scriptpath" to the PowerShell invocation.
Warning
Setting execution policy to Unrestricted or Bypass at machine scope is a security risk in regulated environments. Prefer RemoteSigned, which requires scripts to be digitally signed if downloaded from the internet but allows locally-created scripts to run. Work with your security team to establish an approved policy before deploying to production.
If you start monitoring immediately after submitting a print job, the job may not have entered the spooler yet when the first WMI poll runs. The 3-second wait after submission shown in the exercise handles most cases, but very slow machines or congested print servers may need 5-10 seconds. If you're seeing JOB_NOT_FOUND on fast-printing documents, increase the pre-poll wait and re-test.
You now have a complete, production-ready approach to printer automation in Power Automate Desktop. The key architecture you've built:
Get-Printer via PowerShell before attempting anythingWin32_PrintJob.Delete() with retry logicThe techniques here compose naturally with the rest of your automation toolkit. If you're generating the documents you print from within the same flow — say, pulling data and building PDFs — the multi-application workflow patterns show how to chain those steps cleanly. And if this is part of a larger 24/7 unattended operation, the queue-driven orchestration patterns in Building a Resilient Unattended RPA Orchestration Framework in Power Automate Desktop will show you how to dispatch print jobs across multiple machines at scale.
The next logical step is adding monitoring visibility beyond the flow itself — hooking your print log into a Power BI dashboard or setting up automated escalation alerts. That's where this bot transforms from a time-saver into infrastructure your operations team actively trusts.