Powershell Error: "There is not enough memory or disk to complete the operation"

Powershell Error: "There is not enough memory or disk to complete the operation"

我是 运行 一个用于读取多个 word 文档的 powershell 脚本。当运行 大约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()