Basic Powershell - 批量将 Word Docx 转换为 PDF [英] Basic Powershell - batch convert Word Docx to PDF

查看:88
本文介绍了Basic Powershell - 批量将 Word Docx 转换为 PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 PowerShell 将 Word Docx 批量转换为 PDF - 使用在此站点上找到的脚本:http://blogs.technet.com/b/heyscriptingguy/archive/2013/03/24/weekend-scripter-convert-word-documents-to-pdf-files-with-powershell.aspx

I am trying to use PowerShell to do a batch conversion of Word Docx to PDF - using a script found on this site: http://blogs.technet.com/b/heyscriptingguy/archive/2013/03/24/weekend-scripter-convert-word-documents-to-pdf-files-with-powershell.aspx

# Acquire a list of DOCX files in a folder
$Files=GET-CHILDITEM "C:\docx2pdf\*.DOCX"
$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("docx","pdf")

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

而且我不断收到此错误,但不知道为什么:

And I keep on getting this error and can't figure out why:

PS C:\docx2pdf> .\docx2pdf.ps1
Exception calling "SaveAs" with "16" argument(s): "Command failed"
At C:\docx2pdf\docx2pdf.ps1:13 char:13
+     $Doc.saveas <<<< ([ref] $Name, [ref] 17)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

有什么想法吗?

另外 - 我需要如何更改它才能同时转换 doc(不是 docX)文件,以及使用本地文件(与脚本位置位于同一位置的文件)?

Also - how would I need to change it to also convert doc (not docX) files, as well as use the local files (files in same location as the script location)?

抱歉 - 从未做过 PowerShell 脚本...

Sorry - never done PowerShell scripting...

推荐答案

这适用于 doc 和 docx 文件.

This will work for doc as well as docx files.

$documents_path = 'c:\doc2pdf'

$word_app = New-Object -ComObject Word.Application

# This filter will find .doc as well as .docx documents
Get-ChildItem -Path $documents_path -Filter *.doc? | ForEach-Object {

    $document = $word_app.Documents.Open($_.FullName)

    $pdf_filename = "$($_.DirectoryName)\$($_.BaseName).pdf"

    $document.SaveAs([ref] $pdf_filename, [ref] 17)

    $document.Close()
}

$word_app.Quit()

这篇关于Basic Powershell - 批量将 Word Docx 转换为 PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆