Powershell - 文件已存在时的另存为功能

标签 powershell save-as

我正在尝试运行一些代码来查找目录和子目录中的所有 .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/

相关文章:

excel - 使用VB自动化IE "save target as"

windows - Haxe、Stencyl、Windows 'Save As' 对话

powershell - 使用 Powershell 更新 IIS 中的主机 header

PowerShell - 将具有多个值的变量添加到 CSV 列

git - 使用 Windows PowerShell 设置 .SSH key 时出错

windows - 在打印机上启用共享并设置共享名

android - Android Studio 文件菜单中是否有 "Save as"选项?

PowerShell:New-SelfSignedCertificate:CertEnroll::CX509Enrollment::_CreateRequest:指定的标志无效。 0x80090009

vba - 将工作簿副本另存为新的XLSM,运行时错误1004

java - 在不关闭对话框的情况下取消在 JFileChooser 中选择文件