【发布时间】:2016-03-18 13:48:03
【问题描述】:
我有一个用于将 .doc/.docx 文件自动转换为 *.pdf 的 Powershell 脚本。 该脚本对于第一个文件运行良好。但是如果我将另一个文件放在监视文件夹中,则监视程序不会触发事件。
这是完整的脚本。如果我注释掉所有 $doc 变量,脚本会运行多次而没有任何问题。我是否忽略/忽略了什么?
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "$Env:DropboxRoot"
$watcher.Filter = "*.doc*"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
Add-type -AssemblyName Microsoft.Office.Interop.Word
$action = {
$name = (get-item $Event.SourceEventArgs.FullPath).BaseName
### DON'T PROCESS WORD BACKUP FILES (START WITH A TILDE ~)
if(!($name.startsWith("~"))){
write-host Triggered event from $Event.SourceEventArgs.FullPath
$inputFilePath = $Event.SourceEventArgs.FullPath
$parentPath = (get-item $inputFilePath).Directory
$filename = (get-item $inputFilePath).BaseName
$pdfDir = "$parentPath\PDF"
if(!(Test-Path -Path $pdfDir)){
New-Item -ItemType directory -Path $pdfDir
}
###Execute PDF generate script
write-host Create word object
$word = New-Object -ComObject "Word.Application"
######define the parameters######
write-host Define parameters
$wdExportFormat =[Microsoft.Office.Interop.Word.WdExportFormat]::wdExportFormatPDF
$OpenAfterExport = $false
$wdExportOptimizeFor = [Microsoft.Office.Interop.Word.WdExportOptimizeFor]::wdExportOptimizeForOnScreen
$wdExportItem = [Microsoft.Office.Interop.Word.WdExportItem]::wdExportDocumentContent
$IncludeDocProps = $true
$KeepIRM = $false #Don't export Inormation Rights Management informations
$wdExportCreateBookmarks = [Microsoft.Office.Interop.Word.WdExportCreateBookmarks]::wdExportCreateWordBookmarks #Keep bookmarks
$DocStructureTags = $true #Add additional data for screenreaders
$BitmapMissingFonts = $true
$UseISO19005_1 = $true #Export as PDF/A
$outputFilePath = $pdfDir + "\" + $filename + ".pdf"
$doc = $word.Documents.Open($inputFilePath)
$doc.ExportAsFixedFormat($OutputFilePath,$wdExportFormat,$OpenAfterExport,`
$wdExportOptimizeFor,$wdExportRange,$wdStartPage,$wdEndPage,$wdExportItem,$IncludeDocProps,`
$KeepIRM,$wdExportCreateBookmarks,$DocStructureTags,$BitmapMissingFonts,$UseISO19005_1)
$doc.Close()
$word.Quit()
[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($doc)
[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($word)
[GC]::Collect()
[GC]::WaitForPendingFinalizers()
}
}
$created = Register-ObjectEvent $watcher -EventName "Created" -Action $action
$renamed = Register-ObjectEvent $watcher -EventName "Renamed" -Action $action
while($true) {
sleep 5
}`
【问题讨论】:
-
不是一个真正的答案。我对观察者和
Register-ObjectEvent有一些问题,无法解决。所以我使用了不同的方法并创建了工具Watch-Directory.ps1。请看一下,也许你会发现它有用。 -
当您看到问题时,您是否注意到使用任务管理器时 word 实例没有退出?我看不出这会如何影响任何事情,但在 WaitForPendingFinalizers 添加
Remove-Variable doc和Remove-Variable word之后。可能值得将您的代码放入 try/catch/finally 并将您的清理代码放入 finally。添加更多日志记录(文件/写入主机/等)以帮助调试。目前只有我能想到的建议......
标签: windows powershell pdf scripting docx