Powershell - SaveAs function when file already exists

廉价感情. 提交于 2019-12-10 19:16:30

问题


I'm trying to run some code that looks for all .doc & .docx files in a directory & sub-directories and then converts each one to PDF format.

The code below works only if there are no instances of the pdf in these directories i.e. it only works first time. Every subsequent time it fails with:

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

When I delete the previously created PDFs and re-run the PS it works fine. Therefore I can only assume there is a switch or parameter that I'm missing from my SaveAs function which somehow forces the overwrite?

$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()

回答1:


Ok I finally think I've tracked down the problem. It's the Windows Explorer Preview Pane which is locking the file. I had show preview pane turned on the directory where the files were being created and converted, this must have been creating a file lock on the pdf's therefore the script cannot save the new pdf. I turned off preview pane in my Windows Explorer and the script now works repeatedly! Therefore nothing wrong with the Powershell Scripting but thanks for all the input guys. Here's a link to the closest MS KB article that I could find on the subject http://support.microsoft.com/kb/942146




回答2:


try this:

$word.displayalerts = $false
$doc.saveas($path, $wdFormatPDF) # with Word2010 I've to use  $doc.saveas([ref]$path, [ref]$wdFormatPDF)
$word.displayalerts = $true

No error is raised, but I'm using Word2010 I can't test it with other versions




回答3:


There's no flag to overwrite according to the documentation for SaveAs and SaveAs2. So you could just remove it before saving with something like this:

Remove-Item -Path $path -Force -ErrorAction SilentlyContinue
$doc.saveas ($path, $wdFormatPDF) 


来源:https://stackoverflow.com/questions/10317427/powershell-saveas-function-when-file-already-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!