从任务计划程序运行时,PowerShell脚本失败

时间:2019-06-18 03:38:15

标签: powershell scheduled-tasks

在任务计划程序中运行时,PowerShell脚本将XML文件转换为PDF文件(从.bat文件调用)失败,但是在命令提示符下运行正常。

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
)

这应将D:\ FtxData \ ebixprod \ ER \ Output中的所有.xml文件转换为.pdf文件。

如果我在命令提示符下运行.bat文件,效果很好。 当.bat文件在Task Scheduler中运行时挂起-当它命中PowerShell调用时

错误是:

  

您不能在空值表达式上调用方法。

这在以前使用PowerShell 2的服务器上运行良好。 这是Windows 2016,PowerShell 5也是如此。

具有最高特权的运行任务没有什么区别,因为不需要管理员即可运行。

1 个答案:

答案 0 :(得分:0)

请尝试这样更改它。 ps1抱怨您没有传递参数。

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()
相关问题