2017-09-08 76 views
0

我试图使用powershell批量转换大量的docx到pdf,进入不同的目录,同时保持根的文件夹结构。使用powershell批量转换docx到pdf

我有脚本工作,但每10个文档中有大约1个弹出一个“另存为”对话框,我不明白提示保存docx文件,尽管我将可见设置为false。

#Stage the files 
$sourceDir = "C:\Documents\" 
$targetDir = "C:\Temp_Stage\" 

Get-ChildItem $sourceDir -filter "*.doc?" -recurse | foreach{ 
    $targetFile = $targetDir + $_.FullName.SubString($sourceDir.Length); 
    New-Item -ItemType File -Path $targetFile -Force; 
    Copy-Item $_.FullName -destination $targetFile 
} 

#Convert the files 
$wdFormatPDF = 17 
$word = New-Object -ComObject word.application 
$word.visible = $false 
$folderpath = "c:\Temp_Stage\*" 
$fileTypes = "*.docx","*doc" 

Get-ChildItem -path $folderpath -include $fileTypes -Recurse | 
foreach-object { 
$path = ($_.fullname).substring(0,($_.FullName).lastindexOf(".")) 
$doc = $word.documents.open($_.fullname) 
$doc.saveas([ref] $path, [ref]$wdFormatPDF) 
$doc.close() 
} 
$word.Quit() 

有没有办法来抑制所有字的对话框/警告/错误,它应该是一个相当自动的过程已经结束了漂亮的手工工艺。

+0

你可以打印您的变量?也许在$ path/$ _。fullname或$ wdFormatPDF文件中存在错误,导致对话框弹出。 –

+0

另一件需要考虑的事情是,当你说1/10份左右的文件时,它们总是相同还是每次都是随机文件? –

+0

它似乎是两个 - 相同的,随机的,文件从一个共享点lib,然后转换。如果我重新运行相同的文件,生病会得到同样的错误,如果我从共享点新鲜出来,生病会得到不同的文件。它必须是一个文件问题,但我不知道如何追踪确切的问题。 – DDulla

回答

0

我发现你应该在Word-COM命令之间暂停。 我还必须编写一个脚本,Word将文档转换为。点到。 DOTM。 我不仅偶尔会得到保存对话框,还会在控制台中出现很多E_FAIL错误。 休息时间(最长50ms)有很大帮助。 破解PowerShell:

Start-Sleep -m 50 

我希望它能帮助你。

问候 Bloodrayne1995

+0

这确实有些帮助。谢谢。它是完全解决你的保存对话框,还是只是减少它?它并没有完全消除我的... – DDulla