ConvertWordToPdf
public
Jan 17, 2025
Never
16
PowerShell
ConvertWordToPdf.ps1
PowerShell
ConvertWordToPdf.bat
1 $word = New-Object -ComObject Word.Application 2 $word.Visible = $false 3 4 $folderPath = "..\data\source\docx" 5 $outputFolderPath = "..\data\converted" 6 7 # Ensure the output folder exists 8 if (-not (Test-Path -Path $outputFolderPath)) { 9 New-Item -ItemType Directory -Path $outputFolderPath | Out-Null 10 } 11 12 # Get all Word documents in the folder 13 $files = Get-ChildItem -Path $folderPath -Filter *.docx 14 15 foreach ($file in $files) { 16 try { 17 # Open the document 18 $doc = $word.Documents.Open($file.FullName) 19 $pdfFilename = [System.IO.Path]::ChangeExtension($file.Name, ".pdf") 20 $outputPath = [System.IO.Path]::Combine((Get-Item $outputFolderPath).FullName, $pdfFilename) 21 22 # Save the document as PDF (ensure proper types are passed) 23 $doc.SaveAs([string]$outputPath, 17) # 17 is wdFormatPDF 24 $doc.Close() 25 Write-Host "Converted $file to $pdfFilename" 26 } catch { 27 Write-Error ("Failed to convert {0}: {1}" -f $file, $_.Exception.Message) 28 } 29 } 30 31 # Quit Word application 32 $word.Quit()
1 echo on 2 rem "put this script in the same subfolder as ConvertWordToPSF.ps1 script, then double click it from there" 3 powershell -ExecutionPolicy Bypass -File "./ConvertWordToPDF.ps1" 4 pause