简体   繁体   中英

PowerShell script failing when run from the Task Scheduler

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM