如何让这个脚本循环遍历目录中的所有文件?
我相信我是按照我想要的方式保存文件的,但我可以一次保存。
我正在学习Powershell ......
如何将工作簿(excel 2010)中的每个工作表保存为以下格式:文件名+" - " +工作表名称为CSV?
谢谢,
$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);
答案 0 :(得分:1)
我没有测试过,但我认为它应该可行。我已经解释了代码中的变化:
$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);