0

PowerShell script to convert an XML file to a PDF, called from a .bat file fails when run in Task Scheduler, but works fine from a Command Prompt.

Word2PDF.ps1:

$File = $args[0]
$Word = New-Object -ComObject Word.Application

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

$Name = ($Doc.FullName).Replace(".xml", ".pdf")

# Save this File as a PDF in Word
$Doc.SaveAs([ref]$Name, 17)
$Doc.Close()
$Word.Quit()

ReplaceXMLAttachemtnswithPDF.bat:

@echo off

rem Convert XML files and attachments to PDFs

setlocal EnableExtensions
setlocal EnableDelayedExpansion

cd /D "D:\FtxData\ebixprod\ER\Output"

set WORKFILE=C:\Temp\workfile.txt

dir /B *.xml > files.txt 

for /F %%f in ('type files.txt') do (
    echo %%f | ssed s/.xml/.pdf/ > !WORKFILE!
    for /F %%g in ('type !WORKFILE!') do set newfile=%%g

    powershell D:\Ebix\Fintechnix\Bin\Word2Pdf.ps1 D:\FtxData\!DB!\ER\Output\%%f
)

This should convert all .xml files in D:\FtxData\ebixprod\ER\Output to .pdf files.

Works fine if I run the .bat file in a Command Prompt. Hangs when .bat file run in Task Scheduler - when it hits the PowerShell call

Error is:

You cannot call a method on a null-valued expression.

This worked fine on a previous server with PowerShell 2. This is Windows 2016 so has PowerShell 5.

Running task with highest privileges made no difference as does not need admin to run.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Colin Hay
  • 25
  • 3
  • 1
    [Related](https://stackoverflow.com/a/41635982/1630171). Also, which statement exactly is throwing that error? Please show the complete error message. – Ansgar Wiechers Jun 18 '19 at 07:59

1 Answers1

0

Try changing it like this please. The ps1 is complaining that you did not pass in parameters.

Param(
    $File
)
$Word=NEW-OBJECT -COMOBJECT WORD.APPLICATION

# open a Word document, filename from the directory

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

# Swap out XML with PDF in the Filename

$Name=($Doc.Fullname).replace(".xml",".pdf")

# write-host $Name

# Save this File as a PDF in Word

$Doc.saveas([ref]$Name, 17)
$Doc.close()
$Word.Quit()
Sid
  • 2,586
  • 1
  • 11
  • 22