我有一个脚本(下面)将docx转换为PDF。但是,在它到达文件204或205之后,我收到内存超出消息并且进程停止。我有大约40,000个需要转换的docx。有人可以帮助提高效率,或者可能在每150个文档之后添加一个关闭应用程序的循环,然后重新打开应用程序并继续吗?任何帮助将不胜感激。
$documents_path = 'C:\Users\jgentile\Desktop\Purdue\DocX\All'
$word_app = New-Object -ComObject Word.Application
$i=0
Get-ChildItem -Path $documents_path -Filter *.doc? | ForEach-Object {
If( $i%150 ) { $word_app.Quit(); $word_app = New-Object -ComObject Word.Application }
$document = $word_app.Documents.Open($_.FullName)
$pdf_filename = "C:\Users\jgentile\Desktop\Purdue\PDFs\$($_.BaseName)_Discipline.pdf"
$document.SaveAs([ref] $pdf_filename, [ref] 17)
$document.Close()
$i++
}
$word_app.Quit()
答案 0 :(得分:0)
if-test需要true
或false
值。 1%150
将返回1
,2%150
将返回2
等 - > value不为null。 if-test将始终为true,除了0转换为false。因此,您的脚本实际上与您想要的方式相反。
您应该测试$i%150 -eq 0
。这只会在$i
为0,150,300,450等时发生。如果您不希望它在0上运行,请在1开始$i
。)
尝试
If($i%150 -eq 0) { $word_app.Quit(); $word_app = New-Object -ComObject Word.Application }
你也可以使用if(-not($i%150))
翻转if-test(将false变为true),但我认为-eq 0
更具可读性。
UPDATE :正如@ Cole9350指出的那样,你应该在调用Quit()
后释放Comobject以释放资源(进程)上的句柄,以便Word正常关闭。像:
If($i%150 -eq 0) {
$word_app.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($word_app)
$word_app = New-Object -ComObject Word.Application
}
答案 1 :(得分:0)
if语句的设置方式,它将执行循环的每次迭代,除了150,我猜不是你想要的。此外,您应该释放comobject以避免内存不足异常
If(!($i%150)) {
$word_app.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($word_app)
Remove-Variable word_app
$word_app = New-Object -ComObject Word.Application
}