Update2
现在,当我知道x32是我使用powershell_ise_x32调试到脚本中的问题时,发现$Word.Documents是null。因此,Powershell-API for Word在x32 PowerShell中有不同的行为,在64位中则不同。

更新
该错误发生在使用PowerShell x32时,而不发生在PowerShell 64位上。真的是这样。执行Powershell x32是因为我从总指挥官32位启动它。
现在的问题是-为什么32位和64位PowerShell有不同的行为?
初始问题:
我编写了一个powershell脚本,将我的WordDocuments转换成一个。
我编写了一个批处理脚本,以启动这个powershell脚本。
当我在"Powershell ISE“中直接执行脚本时,脚本可以很好地工作。
当我通过上下文菜单以管理员的身份执行批处理脚本时,脚本报告错误。在本例中,执行C:\WINDOWS\SysWOW64\cmd.exe。
当我以管理员的身份执行在我的系统"C:\Windows\WinSxS\amd64_microsoft-windows-commandprompt_31bf3856ad364e35_10.0.15063.0_none_9c209ff6532b42d7\cmd.exe“上找到的另一个cmd.exe时,工作得很好:
为什么我在不同的cmd.exe中有不同的行为?那些不同的cmd.exe是什么?



批处理脚本:
cd /d "%~dp0"
powershell.exe -noprofile -executionpolicy bypass -file "%~dp0%DocxToPdf.ps1"
pausePowershell脚本
$FilePath = $PSScriptRoot
$Pdfsam = "D:\Programme\PDFsam\bin\run-console.bat"
$Files = Get-ChildItem "$FilePath\*.docx"
$Word = New-Object -ComObject Word.Application
if(-not $?){
throw "Failed to open Word"
}
# Convert all docx files to pdf
Foreach ($File in $Files) {
Write-Host "Word Object: " $Word
Write-Host "File Object: " $Word $File
Write-Host "FullName prop:" $File.FullName
# open a Word document, filename from the directory
$Doc = $Word.Documents.Open($File.FullName)
# Swap out DOCX with PDF in the Filename
$Name=($Doc.FullName).Replace("docx","pdf")
# Save this File as a PDF in Word 2010/2013
$Doc.SaveAs([ref] $Name, [ref] 17)
$Doc.Close()
}
# check errors
if(-not $?){
Write-Host("Stop because an error occurred")
pause
exit 0
}
# wait until the conversion is done
Start-Sleep -s 15
# Now concat all pdfs to one single pdf
$Files = Get-ChildItem "$FilePath\*.pdf" | Sort-Object
Write-Host $Files.Count
if ($Files.Count -gt 0) {
$command = ""
Foreach ($File in $Files) {
$command += " -f "
$command += "`"" + $File.FullName + "`""
}
$command += " -o `"$FilePath\Letter of application.pdf`" -overwrite concat"
$command = $Pdfsam + $command
echo $command
$path = Split-Path -Path $Pdfsam -Parent
cd $path
cmd /c $command
}else{
Write-Host "No PDFs found for concatenation"
}
Write-Host -NoNewLine "Press any key to continue...";
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown");发布于 2017-08-05 15:32:43
我发现$PSScriptRoot不可靠。
$FilePath = $PSScriptRoot;
$CurLocation = Get-Location;
$ScriptLocation = Split-Path $MyInvocation.MyCommand.Path
Write-Host "FilePath = [$FilePath]";
Write-Host "CurLocation = [$CurLocation]";
Write-Host "ScriptLocation = [$ScriptLocation]";结果:
O:\Data>powershell ..\Script\t.ps1
FilePath = []
CurLocation = [O:\Data]
ScriptLocation = [O:\Script]至于不同cmd.exe实现之间的差异,我不能真正回答。我应该认为它们在功能上是相同的,但也许有32/64位的差异才是重要的。
发布于 2017-08-06 11:31:10
该错误发生在使用PowerShell x32时,而不发生在PowerShell 64位上。
我使用powershell_ise_x32调试了脚本,发现$Word.Documents是null。
这是因为我的系统上安装了Word 64位。
https://stackoverflow.com/questions/45523112
复制相似问题