In the previous tip we created the function Out-PDFFile which accepts any PowerShell results and turns them into a PDF file – using the built-in printer drivers in Windows 10 and Windows Server 2016.

We used a simple function for this to use the $Input automatic variable to easily access the piped data. If you’d rather like to use an advanced function to take advantage of mandatory parameters, we wrapped the project up in a sophisticated advanced function that also installs the PDF printer if it is still missing:

function Out-PDFFile
{
    param
    (
        [Parameter(Mandatory)]
        [String]
        $Path,

        [Parameter(ValueFromPipeline)]
        [Object]
        $InputObject,

        [Switch]
        $Open
    )

    begin
    {
        # check to see whether the PDF printer was set up correctly
        $printerName = "PrintPDFUnattended"
        $printer = Get-Printer -Name $printerName -ErrorAction SilentlyContinue
        if (!$?)
        {
            $TempPDF = "$env:temp\tempPDFResult.pdf"
            $port = Get-PrinterPort -Name $TempPDF -ErrorAction SilentlyContinue
            if ($port -eq $null)
            {
                # create printer port
                Add-PrinterPort -Name $TempPDF 
            }

            # add printer
            Add-Printer -DriverName "Microsoft Print to PDF" -Name $printerName -PortName $TempPDF 
        }
        else
        {
            # this is the file the print driver always prints to
            $TempPDF = $printer.PortName
            
            # is the port name is the output file path?
            if ($TempPDF -notlike '?:\*')
            {
                throw "Printer $printerName is not set up correctly. Remove the printer, and try again."
            }
        }

        # make sure old print results are removed
        $exists = Test-Path -Path $TempPDF
        if ($exists) { Remove-Item -Path $TempPDF -Force }
        
        # create an empty arraylist that takes the piped results
        [Collections.ArrayList]$collector = @()
    }

    process
    {
        $null = $collector.Add($InputObject)
    }

    end
    {
        # send anything that is piped to this function to PDF
        $collector | Out-Printer -Name $printerName

        # wait for the print job to be completed, then move file
        $ok = $false
        do { 
            Start-Sleep -Milliseconds 500
            Write-Host '.' -NoNewline
                
            $fileExists = Test-Path -Path $TempPDF
            if ($fileExists)
            {
                try
                {
                    Move-Item -Path $TempPDF -Destination $Path -Force -ea Stop
                    $ok = $true
                }
                catch
                {
                    # file is still in use, cannot move
                    # try again
                }
            }
        } until ( $ok )
        Write-Host

        # open file if requested
        if ($Open)
        {
            Invoke-Item -Path $Path
        }
    }
}

Provided you are using Windows 10 or Windows Server 2016, and the “Microsoft Print to PDF” printer is available, you can now create PDF documents as easy as this:

 
PS> Get-Service | Out-PDFFile -Path $home\desktop\services.pdf -Open

PS> Get-ComputerInfo | Out-PDFFile -Path $home\Desktop\computerinfo.pdf -Open 
 

If the special “PrintPDFUnattended” printer is not yet set up, the function takes care of this as well.


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!

Anonymous