Automatically Printing to XPS Files

by Jan 28, 2019

XPS is a document format similar to PDF from Microsoft. Although it never really was used in a large scale, it can still be a valuable internal format to print information to a file. To print unattended to XPS files, first you need to set up a new printer that automatically prints to a specific output file:

#requires -RunAsAdministrator

$OutPath = "$env:temp\out.xps"
$PrinterName = "XPSPrinter"
Add-PrinterPort -Name $OutPath
Add-Printer -Name $PrinterName -DriverName 'Microsoft XPS Document Writer v4' -PortName $OutPath

Also make sure the XPS Viewer is installed:

#requires -RunAsAdministrator
Enable-WindowsOptionalFeature -Online -FeatureName Xps-Foundation-Xps-Viewer -NoRestart

With these prerequisites in place, it is now trivial to automatically print results to XPS files. Here is the print function for a daily use:

function Out-PrinterXPS ($Path = $(Read-Host -Prompt 'XPS document path to create'))
{
  $PrinterName = "XPSPrinter"
  $OutPath = "$env:temp\out.xps"

  $exists = Test-Path -Path $OutPath
  if ($exists)
  {
    Remove-Item -Path $OutPath
  }

  $input | Out-Printer -Name $PrinterName
  do
  {
    Start-Sleep -Milliseconds 500
    $exists = Test-Path -Path $OutPath
  } while (!$exists)

  Move-Item -Path $OutPath -Destination $Path -Force
}

Let’s try it! Here is a one-liner that creates a system inventory report on your desktop:

# print to this file
$Path = "$home\desktop\inventar.xps"

# pipe the data to the file
systeminfo.exe /FO CSV | ConvertFrom-Csv | Out-PrinterXPS -Path $Path

# open the XPS file with the built-in viewer
Invoke-Item -Path $Path

psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip! ReTweet this Tip!