I’m using the following powershell script to open a few thousand HTML files and “save as…” Word documents.
param([string]$htmpath,[string]$docpath = $docpath)
$srcfiles = Get-ChildItem $htmPath -filter "*.htm*"
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatDocument");
$word = new-object -comobject word.application
$word.Visible = $False
function saveas-document
{
$opendoc = $word.documents.open($doc.FullName);
$opendoc.saveas([ref]"$docpath\$doc.FullName.doc", [ref]$saveFormat);
$opendoc.close();
}
ForEach ($doc in $srcfiles)
{
Write-Host "Processing :" $doc.FullName
saveas-document
$doc = $null
}
$word.quit();
The content converts splendidly, but my filename is not as expected.
$opendoc.saveas([ref]"$docpath\$doc.FullName.doc", [ref]$saveFormat); results in foo.htm saving as foo.htm.FullName.doc instead of foo.doc.
$opendoc.saveas([ref]"$docpath\$doc.BaseName.doc", [ref]$saveFormat); yields foo.htm.BaseName.doc
How do I set up a Save As... filename variable equal to a concatenation of BaseName and .doc?
Based on our comments above, it seems that moving the files is all you want to accomplish. The following works for me. In the current directory, it replaces .txt extensions with .py extensions. I found the command here.
You can also change
*.txttoC:\path\to\file\*.txtso you don’t need to execute this line from the location of the files. You should be able to define a destination in a similar manner, so I’ll report back if I find a simple way to do that.Also, I found Microsoft’s TechNet Library while I was searching. It has many tutorials on scripting using PowerShell. Files and Folders, Part 3: Windows PowerShell should help you to find additional info on copying and moving files.