Windows PowerShell脚本将Word Docs的文件夹转换为PDF


2

因此,我已经有了执行此操作的基本代码。即将word docs文件夹转换为pdf。

# Acquire a list of DOCX files in a folder

$Files=GET-CHILDITEM ‘C:\Users\Ashley\downloads\articles\*.DOC’
$Word=NEW-OBJECT –COMOBJECT WORD.APPLICATION


Foreach ($File in $Files) {

    # open a Word document, filename from the directory

    $Doc=$Word.Documents.Open($File.fullname)

    # Swap out DOCX with PDF in the Filename

    $Name=($Doc.Fullname).replace(“doc”,”pdf”)

    # Save this File as a PDF in Word 2010/2013
    $Doc.saveas([ref] $Name, [ref] 17)
    $Doc.close()

}

但是就目前而言,如果我有docx文件。我需要重新运行将doc替换为docx的代码。他们有什么办法可以使replace函数将doc和docx替换为pdf?从而消除了重新运行两次的需要?谢谢!

Answers:


1

这应该有所帮助。注意get-childitem查找doc *,而正则表达式替换。

$Files=GET-CHILDITEM 'C:\Users\Ashley\downloads\articles\*.DOC*'
$Word=NEW-OBJECT –COMOBJECT WORD.APPLICATION

Foreach ($File in $Files) {

    # open a Word document, filename from the directory

    $Doc=$Word.Documents.Open($File.fullname)

    # Swap out DOCX with PDF in the Filename

    $Name=$Doc.Fullname -replace('doc([x]{0,1})',"pdf")

    # Save this File as a PDF in Word 2010/2013
    $Doc.saveas([ref] $Name, [ref] 17)
    $Doc.close()

}

我收到错误异常,并用“ 16”个参数调用“ SaveAs”:“命令失败”在行:17字符:16 + $ Doc.saveas <<<<([ref] $ Name,[ref] 17) + CategoryInfo:未指定:(:) [],MethodInvocationException + FullyQualifiedErrorId:DotNetMethodException
Web Dev

我编辑了代码,并使用-replace。然后,我能够保存到pdf文件。
Micky Balladelli 2014年

@Micky Balladelli,您好:我正在使用您的脚本转换多个docx文件,但失败并显示以下错误:参数“ 1”不应为System.Management.Automation.PSReference。请不要使用[ref]。你能找出原因吗?我使用PS 2在Windows 7
韦恩崔

@WayneCui Word版本可能有所不同吗?您的案例中SaveAs期望的方法是什么?
Micky Balladelli
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.