【发布时间】:2020-01-08 21:29:57
【问题描述】:
这几天让我发疯......我有一个 powershell 脚本,它使用 Word SaveAs 互操作将目标目录中的所有 .doc 文件转换为 PDF。
该脚本在登录用户的上下文中运行时工作正常,但当我尝试执行时出现“您不能在空值表达式上调用方法。”错误使用服务帐户的脚本(通过任务计划程序,以其他用户身份运行)...服务帐户具有本地管理员权限。
异常发生在这一行:$Doc.SaveAs([ref]$Name.value,[ref]17)
我的代码如下,我不是世界上最好的编码器,所以任何建议都将不胜感激。 谢谢。
try
{
$FileSource = 'D:\PROCESSOR\NewArrivals\*.doc'
$SuccessPath = 'D:\PROCESSOR\Success\'
$docextn='.doc'
$Files=Get-ChildItem -path $FileSource
$counter = 0
$filesProcessed = 0
$Word = New-Object -ComObject Word.Application
#check files exist to be processed.
$WordFileCount = Get-ChildItem $FileSource -Filter *$docextn -File| Measure-Object | %{$_.Count} -ErrorAction Stop
If ($WordFileCount -gt 0) {
Foreach ($File in $Files) {
$Name="$(($File.FullName).substring(0, $File.FullName.lastIndexOf("."))).pdf"
$Doc = $Word.Documents.Open($File.FullName)
$Doc.SaveAs([ref]$Name.value,[ref]17)
$Doc.Close()
if ($counter -gt 100) {
$counter = 0
$Word.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Word)
$Word = New-Object -ComObject Word.Application
}
$counter = $counter + 1
$filesProcessed = $filesProcessed + 1
}
}
$Word.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Word)
}
catch
{
}
finally
{
}
【问题讨论】:
标签: powershell ms-word