如何从Powershell中的目录parsing个别的Excel文件

我是PowerShell的全新。 几个小时以来,我一直在努力完成一件看似简单的事情。 我真的很感激一些帮助。

我有一个巨大的文件夹和子文件夹的列表,充满了Microsoft Excel文件* .xlsm,我想从中检索特定的单元格数据。

$Excel_files = (gci C:\Users\xxx\xxx\ -Recurse -File *.xlsm).FullName foreach($getname in $Excel_files) { $Excel = New-Object -ComObject Excel.Application $readbook = $Excel.WorkBooks.Open($Excel_files) $readsheet = $readbook.WorkSheets.Item("SHEET NAME") $Excel.Visible = $false $getname = $readsheet.Cells.Item(8,3) return $getname.text } 

我在正确的轨道上?

其目的是从几千* .xlsm文件中提取名称,date和描述,并将它们放入一个新的单独表单中。

我感谢任何帮助,谢谢。

除了不应该在循环体中使用return之外,你一般是在正确的轨道上,因为它不仅会退出循环,而且还会封闭函数/脚本。

另外,在每个循环迭代中创build一个新的Excel实例效率不高。

重构版本的代码:

 # Determine the target workbooks' sheet name and cell address to extract. $targetSheet = 'SHEET NAME' $row = 8 $col = 3 # Create the Excel instance *once*. $xl = New-Object -ComObject Excel.Application # Loop over all workbooks of interest and extract the information of interest # and collect the values in array $cellVals # (There is no strict need for this intermediate step; omit `$cellValues = ` # to output the values directly.) $cellVals = Get-ChildItem C:\Users\xxx\xxx -File -Recurse -Filter *.xlsm | ForEach-Object { $wb = $xl.WorkBooks.Open($_.fullName) # Output the cell value of interest. $wb.WorkSheets($targetSheet).Cells($row, $col).text $wb.Close() } # Output the collected cell values. $cellVals