Batch convert .txt files to Word documents (PowerShell)

Introduction

This Windows PowerShell script sample shows how to batch convert .txt files to Word documents.

Scenarios

This script shows how to convert many .txt files to Word documents by using Windows PowerShell.

Script

Step 1: Click Start, type powershell in the search box on the Start Menu, right-click the Windows PowerShell icon, and then click Run Windows PowerShell as administrator. When the User Account Control dialog box appears, confirm that the action displayed is correct. Then, click Continue.

Step 2: Run the script in the Windows PowerShell Console, type the command: Import-Module <Script Path>.

For example, type Import-Module G:\Script\ConverTXTFileToWordDocument.psm1

This is shown in the following figure.

Step 3: Type the command to display the help file for this function, such as the syntax, parameters, or examples: Get-Help ConvertTo-OSCWord -Full

Here are some code snippets for your references. To get the complete script sample, please click the download button at the beginning of this page. 

PowerShell
Edit|Remove
Try 
{ 
    #Displays a progress bar within a Windows PowerShell command window. 
    Write-Progress -Activity "Converting txt file [$wdDocumentName] to Word Document" ` 
    -Status "$intNumberTXT of $txtFileCounts TXT File(s)" -PercentComplete $($intNumberTXT/$txtFileCounts*100) 
     
    #Open the Word document 
    $wdDocument = $wdApplication.Documents.Add() 
    $wdSelection = $wdApplication.Selection 
    #Inserting content of txt file 
    $wdSelection.InsertFile($txtFilePath) 
     
    #Save as word document 
    $wdDocument.SaveAs([REF]"$txtFileDirectory\$txtFileBaseName") 
    $wdDocument.Close() 
     
    $Properties = @{'File Name' = $txtFileName 
                    'Convert to Word' = If(Test-Path -Path "$txtFileDirectory\$txtFileBaseName.docx") 
                                        {"Finished"} 
                                        Else 
                                        {"Unfinished"}}         
    $objWord = New-Object -TypeName PSObject -Property $Properties 
    $Objs += $objWord 
    $Objs 
} 
Catch 
{ 
    Write-Warning "'$txtFileName' cannot convert to word document."}

Example

Example 1: Type the ConvertTo-OSCWord -Path C:\TXTFile command in Windows PowerShell Console.

This command will batch convert TXT files to Word documents.

Prerequisite

Windows PowerShell 2.0

Office Word 2010

Additional Resources

New-Object

Word 2010 Developer Reference