Convert-DocxToPDF.ps1
function Convert-DocxToPDF { <# .SYNOPSIS Converts a DOCX file to PDF using WinWord .DESCRIPTION Converts a DOCX file to PDF using WinWord. Supports directories with optional Recursive support. .EXAMPLE Convert-DocxToPDF -file "C:\test.docx" Creates C:\test.pdf .EXAMPLE Convert-DocxToPDF -file "C:\DocsToConvert\" -Recurse Converts any/all DOCX files under C:\DocsToConvert\ and all subfolders. .EXAMPLE Convert-DocxToPDF -file "C:\DocsToConvert\" Converts any/all DOCX files under C:\DocsToConvert\. Subfolders are NOT processed in this example #> [CmdletBinding()] param ( [Parameter(Mandatory=$true, Position=0)] [System.String] $file, [Parameter(Mandatory=$false, Position=1)] [Switch] $Recurse = $false ) if ($file.EndsWith(".docx")) { # A single file was passed. Put this into $Files $Files = Get-Item $file } if (!$file.EndsWith(".docx")) { # A directory was passed. See if [Switch]$Recurse was passed. if ($Recurse) { # Recurse flag passed. Set $Files $Files = Get-ChildItem "$file\*.docx" -Recurse } ELSE { # Recurse NOT passed. Set $Files $Files = Get-ChildItem "$file\*.docx" } } Foreach ($f in $Files) { #Read-Host $f.FullName # open a Word document, filename from the directory $Word=NEW-OBJECT –COMOBJECT WORD.APPLICATION $word.Visible = $true #Read-Host Create word start-sleep -Milliseconds 100 $Doc=$Word.documents.Open($f.fullname) #Read-Host open file $doc start-sleep -Milliseconds 100 # Swap out DOCX with PDF in the Filename start-sleep -Milliseconds 100 $Name=($Doc.Fullname).replace(“.docx”,”.pdf”) #Read-Host Replace DOCX - name is now $Name start-sleep -Milliseconds 100 # Save this File as a PDF in Word 2010/2013 $Doc.saveas([ref] $Name, [ref] 17) #Read-Host Actually save the PDF to $Name $Doc.close() write-host open the file $Name #.$Name #Read-Host Next Time? Write-Host $name gps *winword* | kill -Force -Verbose start-sleep -Milliseconds 100 (gps *winword*).count } } |