Q:

Windows PowerShell Script to convert a folder of Word Docs to PDF

So I already have the basic code to do this. i.e. convert a folder of word docs to pdf.
# Acquire a list of DOCX files in a folder

$Files=GET-CHILDITEM ‘C:\Users\Ashley\downloads\articles\*.DOC’
$Word=NEW-OBJECT –COMOBJECT WORD.APPLICATION

Foreach ($File in $Files) {

    # open a Word document, filename from the directory

    $Doc=$Word.Documents.Open($File.fullname)

    # Swap out DOCX with PDF in the Filename

    $Name=($Doc.Fullname).replace(“doc”,”pdf”)

    # Save this File as a PDF in Word 2010/2013
    $Doc.saveas([ref] $Name, [ref] 17)
    $Doc.close()

}

But as it stands if I have docx files. I need to re run the code replacing doc with docx.
Is their any way I can make the replace function replace doc and docx for pdf? Thus eliminating the need to re run it twice? Thank you!

A:

This should help. Notice get-childitem looks for doc*, and the regex in the replace.
$Files=GET-CHILDITEM 'C:\Users\Ashley\downloads\articles\*.DOC*'
$Word=NEW-OBJECT –COMOBJECT WORD.APPLICATION

Foreach ($File in $Files) {

    # open a Word document, filename from the directory

    $Doc=$Word.Documents.Open($File.fullname)

    # Swap out DOCX with PDF in the Filename

    $Name=$Doc.Fullname -replace('doc([x]{0,1})',"pdf")

    # Save this File as a PDF in Word 2010/2013
    $Doc.saveas([ref] $Name, [ref] 17)
    $Doc.close()

}

