-->

Converting .rtf files to .doc and then .doc back t

2020-08-01 05:16发布

问题:

I need to create a script in powershell with which will convert all my files from .rtf to .doc and then back. I want to do it because I have applied registry fix which will decrease size of my rtf files after such conversion ( It will not save second WMF image specyfic info http://support.microsoft.com/kb/224663 ).I imagine my script workflow as RTF_1 save to doc then close rtf1 delete rtf 1 , save doc to rtf2 , close doc , delete doc.

回答1:

Here is the final working script ( without deleting , I decided I do not need it )

param([string]$rtfpath,[string]$docpath = $rtfpath,[string]$docpath2 = $rtfpath2)
$srcfiles = Get-ChildItem $rtfPath -filter "*.rtf"
$docfiles = Get-ChildItem $docPath -filter "*.doc"
$saveFormat =[Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatDocument");
$saveFormat_back =[Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatRTF");
$word = new-object -comobject word.application
$word.Visible = $False
function saveas-DOC
     {

  $name = $rtf.basename
  $savepath ="$docpath\rtf" + $name + ".doc"
  write-host $name
  Write-Host $savepath
         $opendoc = $word.documents.open($rtf.FullName);
         $opendoc.saveas([ref]$savepath, [ref]$saveFormat);
         $opendoc.close();
     }

function saveas-back_to_rtf
{
         $name = $doc.basename
   $savepath2 ="$rtfpath2\doc" + $name + ".rtf"
   write-host $name
   Write-Host $savepath
         $opendoc = $word.documents.open($doc.FullName);
         $opendoc.saveas([ref]$savepath2, [ref]$saveFormat_back);
         $opendoc.close();

}

ForEach ($rtf in $srcfiles)
     {
         Write-Host "Processing :" $rtf.FullName
         saveas-DOC

     }

ForEach ($doc in $docfiles)
     {
         Write-Host "Processing doc file :" $doc.FullName
         saveas-back_to_rtf
         $doc = $null
     }


$word.quit();