我正在尝试运行一些代码来查找目录和子目录中的所有 .doc 和 .docx 文件,然后将每个文件转换为 PDF 格式。
以下代码仅在这些目录中没有 pdf 实例时才有效,即它仅在第一次有效。随后每次失败时:
Exception calling "SaveAs" with "2" argument(s): "Command failed" At C:\convert\convertword.ps1:12 char:13 + $doc.saveas <<<< ($path, $wdFormatPDF) + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ComMethodTargetInvocation
当我删除之前创建的 PDF 并重新运行 PS 时,它工作正常。因此,我只能假设我的 SaveAs
函数中缺少一个开关或参数,它以某种方式强制覆盖?
$wdFormatPDF = 17
$word = New-Object -ComObject word.application
$word.visible = $false
$folderpath = "c:\convert\*"
$fileTypes = "*.docx","*doc"
Get-ChildItem -path $folderpath -recurse -include $fileTypes |
foreach-object `
{
$path = ($_.fullname).substring(0,($_.FullName).lastindexOf("."))
"Converting $path to pdf ..."
$doc = $word.documents.open($_.fullname)
$doc.saveas($path, $wdFormatPDF)
$doc.close()
}
$word.Quit()
最佳答案
好吧,我想我终于找到了问题所在。锁定文件的是 Windows Explorer Preview Pane。我在创建和转换文件的目录上打开了显示预览 Pane ,这一定是在 pdf 上创建了一个文件锁,因此脚本无法保存新的 pdf。我在我的 Windows 资源管理器中关闭了预览 Pane ,脚本现在可以重复运行!因此,Powershell 脚本没有错,但感谢所有输入的人。这是我能找到的关于该主题的最近的 MS 知识库文章的链接 http://support.microsoft.com/kb/942146
关于Powershell - 文件已存在时的另存为功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10317427/