首页 > 解决方案 > 在 Windows 10 服务中运行 PowerShell 脚本以将 docx 转换为 pdf

问题描述

我有一个将 docx 转换为 pdf 的 powershell 脚本。在 Windows 10 上的用户会话中运行时,它运行没有问题。但是,我需要在 Windows 服务中运行它。

$docx_filename = 'C:\temp\doc2pdf.docx'
$pdf_filename = 'C:\temp\doc2pdf1.pdf'

$word_app = New-Object -ComObject Word.Application

$document = $word_app.Documents.Open($docx_filename)
$document.SaveAs([ref] $pdf_filename, [ref] 17)
$document.Close()

$word_app.Quit()

使用以下命令调用该脚本

powershell.exe -executionpolicy Bypass -NoProfile -NoLogo -NonInteractive -WindowStyle Hidden -File -File "docx2pdf.ps1" -docxFilename "docx2pdf.docx" -pdfFilename "docx2pdf.pdf"

使用 PSSet-Debug -Trace 2 记录以下内容

DEBUG:   14+   >>>> $word_app = New-Object -ComObject Word.Application
DEBUG:     ! SET $word_app = 'Microsoft.Office.Interop.Word.ApplicationClass'.
DEBUG:   16+   >>>> $document = $word_app.Documents.Open($docxFilename)

如何让它在 Windows 10 服务中工作?

谢谢

标签: powershellwindows-services

解决方案


您必须在服务的登录选项卡上设置一个帐户。请务必指定一个您可以交互登录并成功运行 Powershell 脚本的帐户(即您安装 Word 的位置)。

但是即使进行了这种更改,您仍然可能会遇到麻烦,因为 Office并不完全适合在 Windows 服务中运行。有些事情有效,但有些事情却没有。试试看,让我们知道您的进展情况。


推荐阅读