Powershell 打开文本文件并在退出时打印

Powershell Open text file print it on exit

我有一个文本文件需要在 Notepad.exe 中打开并让用户向其中添加一些输入。然后我想在用户退出文件时将文件打印到 Adob​​ePDF。

这是我必须打开的文件

Start-Process notepad.exe C:\path\to\text\file\MyTextFile.txt -NoNewWindow -Wait

不确定如何在退出时打印 PDF。 AdobePDF 是已安装的打印机,但它不是默认打印机。任何帮助或提示将不胜感激。

你可以这样试试,

$TxtFilePath = "C:\folder\txtfile.txt"
Start-Process notepad.exe $TxtFilePath -NoNewWindow -Wait #Assuming user save the file
Get-Content -Path $TxtFilePath| Out-Printer PDFCreator #PDFCreator is the printer name for PDF 

--编辑--

我想不出保留文件名的直接方法,有点用 ms word 写了一个 hack,

Function Save-TxtAsPDF
{
    Param([string] $FilePath, [string] $OutFolder)

    # Required Word Variables
    $ExportASPDFConstant = 17
    $DoNotSaveConstant = 0

    # Create a hidden Word window
    $word = New-Object -ComObject word.application
    $word.visible = $false

    # Add a Word document
    $doc = $word.documents.add()

    # Put the text into the Word document
    $txt = Get-Content $FilePath
    $selection = $word.selection
    $selection.typeText($txt)

    # Set the page orientation to landscape
    $doc.PageSetup.Orientation = 1

    $FileName = (Split-Path -Path $FilePath -Leaf).Replace(".txt",".pdf")  


    $DestinationPath = Join-Path $OutFolder $FileName

    # Export the PDF file and close without saving a Word document
    $doc.ExportAsFixedFormat($DestinationPath,$ExportASPDFConstant)
    $doc.close([ref]$DoNotSaveConstant)
    $word.Quit()
}


$TxtFilePath = "C:\folder\tt.txt"
$OutFolder = "C:\Outputfolder"

Start-Process notepad.exe $TxtFilePath -NoNewWindow -Wait #Assuming user save the file

Save-TxtAsPDF -FilePath $TxtFilePath -OutFolder $OutFolder

看看有没有帮助!