Batch convert Word documents to PDF

PowerShell%20logoSometimes you need to do something that is related to SharePoint. Today I needed to convert a bunch of Word documents to PDF documents. I could have written an application to do this but I wanted to try it with the help of PowerShell.

It is really easy to achieve this with a script:

 

$wdFormatPDF = 17
$word = New-Object -ComObject word.application
$word.visible = $false
$folderpath = "J:\Temp\Convert to PDF\*"
$fileTypes = "*.docx","*.doc"
$ProcessedFolderPath="J:\Temp\Convert to PDF\processedfiles\"
$NewFilePath=""
Get-ChildItem -path $folderpath -include $fileTypes |
foreach-object `
{
try{
	
	$path =  ($_.fullname).substring(0,($_.FullName).lastindexOf("."))
	

 if(!(Test-Path $_.fullname.replace("docx","pdf").replace("doc","pdf"))){
	 
	 "Converting $path to pdf ..."
	 $doc = $word.documents.open($_.fullname)
	 Write-Host $_.fullname.replace("docx","pdf").replace("doc","pdf")  -foregroundcolor green
	 $doc.saveas([ref] $_.fullname.replace("docx","pdf").replace("doc","pdf"), [ref]$wdFormatPDF)
	 $doc.close()
	 
	 #MOVE FILE
	$NewFilePath=$ProcessedFolderPath + $_.Name
	Write-Host "move to: " $NewFilePath -foregroundcolor yellow
	move-item -path $_.fullname -destination $NewFilePath
	
 }else{
	
	
	"file exists ... skipping this one..."	
	#Rename-Item -path $_.fullname -newname $NewFileName
	$NewFilePath=$ProcessedFolderPath + $_.Name
	Write-Host "move to: " $NewFilePath -foregroundcolor yellow
	move-item -path $_.fullname -destination $NewFilePath
	
 }
 
}Catch [system.exception]
 {
  Write-Host "--> error"  -foregroundcolor red
 }

}
$word.Quit()