param( [Parameter(Mandatory=$true)][string]$InputDirectory, [Parameter(Mandatory=$true)][string]$PdfDirectory ) $ErrorActionPreference = 'Stop' New-Item -ItemType Directory -Force -Path $PdfDirectory | Out-Null $word = New-Object -ComObject Word.Application $word.Visible = $false $word.DisplayAlerts = 0 try { foreach ($file in Get-ChildItem -LiteralPath $InputDirectory -Filter '*.docx') { $doc = $word.Documents.Open($file.FullName, $false, $true) try { $doc.Repaginate() $pdf = Join-Path $PdfDirectory ($file.BaseName + '.pdf') $doc.ExportAsFixedFormat($pdf, 17) } finally { $doc.Close($false) [System.Runtime.InteropServices.Marshal]::ReleaseComObject($doc) | Out-Null } } } finally { $word.Quit() [System.Runtime.InteropServices.Marshal]::ReleaseComObject($word) | Out-Null [GC]::Collect() [GC]::WaitForPendingFinalizers() }