Last active
May 2, 2023 22:17
-
-
Save mavaddat/499a0a7f85407705213e5cd370cd803c to your computer and use it in GitHub Desktop.
Txt to Word Doc using PowerShell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Requires -Modules Pscx | |
# First load MS Office base assemblies into the environment | |
Add-Type -Path $env:WINDIR\assembly\GAC_MSIL\office\*\office.dll -PassThru # Use -PassThru to verify it worked (otherwise, fails silently) | |
# Then, add the target MS Word assembly | |
Get-ChildItem -Path $env:windir\assembly -Recurse -Filter Microsoft.Office.Interop.Word* -File | ForEach-Object { | |
Add-Type -LiteralPath ($_.FullName) -PassThru # PassThru again to verify | |
} | |
$wordApp = New-Object -ComObject Word.Application | |
if($null -eq $wordApp){ | |
Write-Host "Failed to create Word.Application object" | |
exit | |
} | |
foreach ($txt in Get-ChildItem -Path . -Filter *.txt) | |
{ | |
try | |
{ | |
$wordDoc = $wordApp.Documents.Add() | |
$wordDocWindow = $wordDoc.ActiveWindow | |
$wordDocWindow.Selection.InsertFile(('"' + ($txt | Get-ShortPath | Select-Object -ExpandProperty ShortPath ) + '"')) | |
$wordDoc.SaveAs([ref]$(Join-Path $txt.Directory.FullName -ChildPath $txt.BaseName)) | |
} | |
catch | |
{ | |
Write-Host $_.Exception.Message | |
} | |
} | |
$wordApp.Quit() | |
[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($wordApp) | |
[GC]::Collect() | |
[GC]::WaitForPendingFinalizers() | |
$wordApp = $null | |
Remove-Variable wordApp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment