我有一个Powershell脚本,用于自动将.doc / .docx文件转换为* .pdf。 该脚本运行良好的第一个文件。 但是如果我把另一个文件放在监视文件夹中,监视器不会触发一个事件。
这是完整的脚本。 如果我注释掉所有$ docvariables,脚本就会多次运行而不会有任何问题。 我忽略了/忽略了什么?
$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 = "$parentPathpdf" 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 }`
Shell脚本删除小于x kb的文件
什么是PowerShell相当于bash的exec()?
如何以编程方式确定从脚本安装的IE版本
在Powershell中使用Get-EventSubscriber cmdlet
我怎样才能通过WinXP批处理脚本可靠地valIDation目录的存在?
在不同组的行之间添加空白行
你将如何编写一个.bat或.cmd文件从PATH中删除一个元素?
在string中查找模式,然后将string放在variables中
是否有可能重写hashbang / shebangpath行为
适用于windows的通用脚本语言
您的脚本有一些问题,更多的调试逻辑可以找到。
在某些情况下, (Get-Item System.Management.automation.PSEventArgs.sourceEventArgs.FullPath)返回null。 由于未知的原因,这似乎发生一次每个文件被转换。 也许它与“〜Temp”文件有关。
随后, if(!($name.startsWith("~")会抛出异常。
当你使用$inputfilePath = $Event.sourceEventArgs.FullPath ,你的变量是一个fileInfo,你真的想要传递一个字符串到$word.documents.Open($inputfilePath) 。
最后,有时Basename是空的。 不知道为什么,但代码可以测试,或使用其他手段剖析FullPath获取名称和路径部分。
所有这一切说,一旦你得到这个工作,我个人的经验是调用Word上的COM对象来做PowerShell中的这种转换是不可靠的(Word挂起,〜Temp文件被留下,你必须从任务管理器杀死Word,在PowerShell中的COM调用永远不会返回) 。 我的测试显示,调用C#控制台应用程序进行转换要可靠得多。 你可以完全用C#编写这个目录观察器和转换器,并完成相同的任务。
假设您仍想将两者,一个PowerShell观察器和一个C#Word to pdf转换器相结合,下面是我提出的一个解决方案。 该脚本运行大约一分钟,以便您可以在ISE或控制台中进行测试。 从控制台按一个键退出。 在退出之前,通过注销在ISE中测试的相当有用的事件,脚本干净地退出。 根据您打算如何运行该脚本来相应地更改。
PowerShell观察者
$watcher = New-Object System.IO.fileSystemWatcher $watcher.Path = "d:testdocconvertsrc" $watcher.Filter = "*.doc*" $watcher.IncludeSubdirectorIEs = $true $watcher.EnableRaisingEvents = $true # copy this somehwere appropriate # perhaps in same directory as your script # put on a read-only share,etc. $wordTopdf = 'd:testdocconvertWordTopdfWordTopdfbinDeBUGWordTopdf.exe' $action = { try { Write-Host "Enter action @ $(Get-Date)" $fullPathObject = (Get-Item $Event.sourceEventArgs.FullPath) if (!($fullPathObject)) { Write-Host "(Get-Item $Event.sourceEventArgs.FullPath) returned null." return } $fullPath = ($fullPathObject).ToString() Write-Host "Triggered event from $fullPath" $filename = Split-Path $FullPath -Leaf if ($filename -and ($filename.StartsWith("~"))) { Write-Host "SkipPing temp file" return } # put pdf in same dir as the file # can be changed,but a lot easIEr to test this way $pdfDir = Split-Path $FullPath -Parent $basename = [System.IO.Path]::GetfilenameWithoutExtension($filename) $outputfilePath = Join-Path $pdfDir $($basename + ".pdf") Write-Host "outputfilePath is: '$outputfilePath'" # call c# WordTopdf to do conversion because # it is way more reliable than similar calls # from PowerShell & $wordTopdf $fullPath $outputfilePath if ($LASTEXITCODE -ne 0) { Write-Host "Conversion result: FAIL" } else { Write-Host "Conversion result: OK" } } catch { Write-Host "Exception from ACTION:`n$($_ | Select *)" } finally { Write-Host "Exit action @ $(Get-Date)" } } $created = Register-ObjectEvent $watcher -Eventname "Created" -Action $action $renamed = Register-ObjectEvent $watcher -Eventname "Renamed" -Action $action $count = 12 while($count--) { Write-Output "run/sleep ($count)..." sleep 5 # will exit from console,not ISE if ([console]::KeyAvailable) { $key = [console]::ReadKey() break } } $created | % {Unregister-Event $_.name} $renamed | % {Unregister-Event $_.name}
C#WordTopdf转换器
为参数添加适当的错误检查…
添加引用到COM Microsoft.Office.Interop.Word
using System; using Microsoft.Office.Interop.Word; namespace WordTopdf { class Program { static int Main(string[] args) { Console.Writeline($"Converting: {args[0]} to {args[1]}"); var conversion = new documentConversion(); bool result = conversion.WordTopdf(args[0],args[1]); if (result) { return 0; } else { return 1; } } } public class documentConversion { private Microsoft.Office.Interop.Word.Application Word; private object UnkNown = Type.Missing; private object True = true; private object False = false; public bool WordTopdf(object Source,object Target) { bool ret = true; if (Word == null) Word = new Microsoft.Office.Interop.Word.Application(); try { Word.Visible = false; Word.documents.Open(ref Source,ref UnkNown,ref True,ref UnkNown); Word.Application.Visible = false; Word.windowstate = Wdwindowstate.wdwindowstateMinimize; #if false object saveFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatpdf; Word.Activedocument.SaveAs(ref Target,ref saveFormat,ref UnkNown); #else Word.Activedocument.ExportAsFixedFormat( (string)Target,WdExportFormat.wdExportFormatpdf,false,WdExportoptimizefor.wdExportoptimizeforOnScreen,WdExportRange.wdExportAlldocument,WdExportItem.wdExportdocumentContent,true,WdExportCreateBookmarks.wdExportCreateWordBookmarks,true); #endif } catch (Exception e) { Console.Writeline(e.Message); ret = false; } finally { if (Word != null) { // close the application Word.Quit(ref UnkNown,ref UnkNown); } } return ret; } } }
总结以上是内存溢出为你收集整理的将Word文档/ docx文件转换为PDF时,文件系统监视器停止工作全部内容,希望文章能够帮你解决将Word文档/ docx文件转换为PDF时,文件系统监视器停止工作所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)