我的任务是创建一个 power shell 脚本,该脚本可以从命令提示符运行,该脚本将使用 Microsoft Word (2013) 打开指定的 word 文档并将其保存为 PDF 文档。
第一次使用 PowerShell,但我成功地创建了一个简短的脚本来完成这项工作,如下所示……
$word=new-object -comobject word.application
$doc=$word.documents.Open("c:\TEST.docx")
$doc.SaveAs([ref]"c:\test.pdf", [ref]17)
$doc.Close()
$word.Quit()
曾经保存为 ps1 文件的文件在使用以下命令运行时效果很好......
powershell.exe -ExecutionPolicy ByPass -file c:\SaveToPDF.ps1
然而,我随后也被要求允许此脚本在远程计算机上运行。所以我已经开始研究这个功能,并且已经能够创建另一个 power shell 脚本,它将在远程计算机上运行命令行作业,如下所示,它将运行帮助命令
$Username = "Username"
$Password = "PWD123"
$ComputerName = "PC-RemoteApps"
$Script = {help}
$SecurePassWord = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $Username, $SecurePassWord
$Session = New-PSSession -ComputerName $ComputerName -credential $Cred
$Job = Invoke-Command -Session $Session -Scriptblock $Script
echo $Job
Remove-PSSession -Session $Session
这也有效,帮助命令的结果会回显到本地 PC。因此,下一步是简单地更改 $Script 变量以包含我希望运行的命令,以执行将 Word 文档转换为 PDF 的操作,如下所示……
$Script = {powershell.exe -ExecutionPolicy ByPass -file c:\SaveToPDF.ps1}
但是,这会产生一个错误(见下文),当在远程 PC 上运行时,看看脚本是如何工作的并没有多大意义......
您不能在空值表达式上调用方法。
- CategoryInfo : NotSpecified: (You cannot call...ued expression.:String) [], remoteException
- FullyQualifiedErrorId : NativeCommandError
在 C:\SaveToPDF.ps1:4 char:12
$doc.SaveAs <<<< ([ref]"c:\test.pdf", [ref]17)
- CategoryInfo : InvalidOperation: (saveas:String) [], 运行时异常
- FullyQualifiedErrorId : InvokeMethodOnNull
您不能在空值表达式上调用方法。
在 C:\SaveToPDF.ps1:5 char:11
$doc.Close <<<< ()
- 类别信息:无效操作:(关闭:字符串)[],运行时异常
- FullyQualifiedErrorId : InvokeMethodOnNull
我什至尝试过将power shell脚本命令直接包含到远程处理脚本中,如下……
$Script = {
$word=new-object -comobject word.application
$doc=$word.documents.Open("c:\TEST.docx")
$doc.SaveAs([ref]"c:\test.pdf", [ref]17)
$doc.Close()
$word.Quit()
我仍然得到一个错误,基本上告诉我同样的事情,如下......
您不能在空值表达式上调用方法。
- 类别信息:无效操作:(另存为:字符串)[],运行时异常
- FullyQualifiedErrorId : InvokeMethodOnNull
您不能在空值表达式上调用方法。
- 类别信息:无效操作:(关闭:字符串)[],运行时异常
- FullyQualifiedErrorId : InvokeMethodOnNull
在我看来 $doc 变量似乎没有设置任何值,因此无法调用 SaveAs() 和 Close() 方法。然而,源文件(“c:\TEST.docx”)存在于远程 PC 上的这个位置,并且在远程 PC 上运行时命令运行正常。
我什至将测试文件移动到本地和远程 PC 都具有读写访问权限的网络位置,但我仍然遇到相同的错误集。
所以在这一点上,我来找你们,看看你们是否能让我知道我错过了什么。
希望能帮到你
谢谢
卡尔
最佳答案
很遗憾,您无法使用 Invoke-Command
或 Enter-PSSession
创建 comobject word.application
。 Word 或任何其他 Office 产品依赖于启动其二进制文件的 GUI 环境。
我真的很想用引文来支持这一点,但可惜我什么都没有..
关于session - 使用 Powershell 在远程计算机上运行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24057959/