所以我已经有了执行此操作的基本代码。即将一个文件夹中的 word 文档转换为 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。有什么方法可以让替换函数将 doc 和 docx 替换为 pdf?这样就无需重新运行两次了?谢谢!
答案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()
}