Archive
Archive for April, 2016
PowerShell script to save all .pdf’s as .docx in and underneath a folder failing on Word 2016, working on Word 2010.
2016/04/02
Leave a comment
- Problem: Word 2016 shows erratic behavior when trying to save (admittedly: complex) .PDF as .DOCX – whether
- using automation
- “The object invoked has disconnected from its clients. (Exception from HRESULT: 0x80010108 (RPC_E_DISCONNECTED))”
- “The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)”
- or trying manually.
- “There is a problem saving the file.”
- “A file error has occurred.”
- Or Word crashes.
- using automation
- Workaround: My age-old Word 2010 installation on Windows Vista with PowerShell 2 (gasp!
) manages this automation script (inspired by The Scripting Guy) just fine:
$Word = NEW-OBJECT –COMOBJECT WORD.APPLICATION
# Acquire a list of DOCX files in a folder
$Files = GET-CHILDITEM -include *.pdf -exclude *_converted.pdf -recurse -path 'G:\bookz\office\excel' # 'G:\bookz\lang\vba' # 'G:\bookz\office\access' #
Foreach ($File in $Files) {
try{
write-host "Trying " $File.fullname
# open a Word document, filename from the directory
$Doc1=$Word.Documents.Open($File.fullname)
write-host "Opening " $File.fullname ". RESULT=" + $?
# Swap out PDF with DOCX in the Filename
$Name=($File.Fullname).replace("pdf",“docx”) # $Name=($Doc1.Fullname).replace("pdf",“docx”)
# Save this File as a PDF in Word 2010/2013 - hm, and 2016 fails?
$Doc1.saveas([ref] $Name, [ref] 16) # see WdSaveFormat enumeration : 16 is word default,
}
catch
{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
write-host "Caught error saving " $FailedItem ". Msg: " $ErrorMessage
}
finally {
$Doc1.close()
[GC]::Collect() # watch me trying a number of things to get this to work with Word 2016... 🙂
move-item -path $file.FullName -destination ($file.Directory.ToString() + "\" + $file.BaseName + "_converted" + $file.Extension)
}
}
Categories: service-is-programming, sourcecode
converting, ms-powershell, MS-Word, pdf

