Powershell - SaveAs function when file already exists

I am trying to run some code that looks for all .doc and .docx files in a directory and subdirectories, and then converts them to PDF.

The code below only works if there are no pdf instances in these directories, i.e. it only works for the first time. Each time it fails:

Raising a SaveAs exception with argument 2: Command Error In C: \ convert \ convertword.ps1: 12 char: 13 + $ doc.saveas <<($ path, $ wdFormatPDF) + CategoryInfo: NotSpecified: (: ) [], MethodInvocationException + FullyQualifiedErrorId: ComMethodTargetInvocation

When I delete previously created PDF files and re-launch PS, it works fine. Therefore, I can only assume that there is a switch or parameter that I miss from my function SaveAs, which somehow forces overwriting?

$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()
+3
source share
3 answers

, , , , . Windows, . , , , , pdf, script pdf. Windows, script ! Powershell, . MS KB, http://support.microsoft.com/kb/942146

+2

:

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

, Word2010. .

+1

There is no flag to overwrite according to the documentation for SaveAs and SaveAs2 . Therefore, you can simply delete it before saving something like this:

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

All Articles