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-Milliseconds500 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 } } }
假设您使用的是 Windows 10 或 Windows 2016,并且 “Microsoft Print to PDF” 打印机可用,那么您可以像这样方便地创建 PDF 文档: