如何使这个脚本遍历目录中的所有文件?

我怎样才能让这个脚本遍历目录中的所有文件?

我相信我是按照自己想要的方式来保存文件的,但我可以一次完成。

我正在学习Powershell …

如何将工作簿(excel 2010)中的每个工作表保存为以下格式:文件名+“ – ”+表格名称为CSV?

  • 我在一些工作簿上每个工作簿最多有3个工作表(可能更多…)
  • 是否有一个最佳的方式来执行此操作?

谢谢,

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition Add-Type -AssemblyName Microsoft.Office.Interop.Excel $excel = new-object -ComObject "Excel.Application"; $excel.DisplayAlerts=$True; $excel.Visible =$false; $wb = $excel.Workbooks.Open($scriptPath + "\1B1195.xlsb"); foreach($ws in $wb.Worksheets) { if($ws.name -eq "OP10" -or $ws.name -eq "OP20" -or $ws.name -eq "OP30") { Write-Host $ws.name; $ws.SaveAs($scriptPath + "\" + $wb.name + "-" + $ws.name + ".csv", [Object] [Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSVMSDOS); } } $wb.close($False) $excel.Quit(); [void][System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel); 

我还没有testing过,但我认为它应该工作。 我已经解释了代码中的更改:

 $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition Add-Type -AssemblyName Microsoft.Office.Interop.Excel $excel = new-object -ComObject "Excel.Application"; $excel.DisplayAlerts=$True; $excel.Visible =$false; #Find every xlsb file in $scriptpath. #If you want to search through subdirectories also, add " -Recurse" before "| Foreach-Object" Get-ChildItem -Path $scriptPath -Filter ".xlsb" | ForEach-Object { #Inside this loop, $_ is the processed xlsb-file. #$_.Fullname includes the full path, like c:\test\myexcelfile.xlsb" #File-specific code $wb = $excel.Workbooks.Open($_.FullName); foreach($ws in $wb.Worksheets) { if($ws.name -eq "OP10" -or $ws.name -eq "OP20" -or $ws.name -eq "OP30") { Write-Host $ws.name; $ws.SaveAs($scriptPath + "\" + $wb.name + "-" + $ws.name + ".csv", [Object] [Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSVMSDOS); } } $wb.close($False) #End file-specific code } $excel.Quit(); [void][System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel);