我正在运行Powershell脚本来读取多个Word文档。当运行大约700个文档时,它显示错误“没有足够的内存或磁盘来完成操作”。
这是我的代码
$excel = New-Object -ComObject Excel.application
$source = 'powershell/attachments'
$docs = Get-ChildItem -Path $source -Recurse -Filter *cover*.docx
$XL = New-Object -ComObject Excel.Application
#Open the workbook
$WB = $XL.Workbooks.Open("powershell/result.xlsx")
#Activate Sheet1, pipe to Out-Null to avoid 'True' output to screen
$WB.Sheets.Item("Sheet1").Activate() | Out-Null
$SearchArray = @('employment', 'source of income', 'US address', 'residential address', 'ID', 'driver license', 'visa', 'passport', 'I-20', 'Social Security Card', 'information update form', 'w9', 'w8', 'tax', 'email address')
$word = New-Object -ComObject Word.application
foreach ($doc in $docs) {
$Document = $word.Documents.Open($doc)
$CVSInfo = $Document.Paragraphs | ForEach-Object{
foreach ($SerchText in $SearchArray) {
$_.Range.Text | Where-Object { $_-match $SerchText} | ForEach-Object {
$_-split ' ' | Select-Object -Last 1
}
}
}
$PathArray = $doc.FullName
#Launch Excel
#Find first blank row #, and activate the first cell in that row
$FirstBlankRow = $($xl.ActiveSheet.UsedRange.Rows)[-1].Row + 1
$XL.ActiveSheet.Range("A$FirstBlankRow").Activate()
#Create PSObject with the properties that we want, convert it to a tab delimited CSV, and copy it to the clipboard
$Record = [PSCustomObject]@{
'ID' = $PathArray
'Context' = $CVSInfo
}
$Record | ConvertTo-Csv -Delimiter "`t" -NoTypeInformation | Clip
#Paste at the currently active cell
$XL.ActiveSheet.Paste() | Out-Null
# Save and close
$WB.Save() | Out-Null
}
$WB.Close() | Out-Null
$XL.Quit() | Out-Null
#Release ComObject
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($XL)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($word)
提前致谢!
最佳答案
您似乎已打开数百个Word文档。不要忘记在循环的每个迭代中将它们关闭:
$Document.Close()
关于powershell - Powershell错误: “There is not enough memory or disk to complete the operation”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64216332/