简体   繁体   English

如何使此脚本循环遍历目录中的所有文件?

[英]How to make this script loop through all files in directory?

How can I make this script loop through all the files in the directory? 如何使该脚本遍历目录中的所有文件?

I believe I got it to save the files the way I want them, but I can do it one at time. 我相信我可以用想要的方式保存文件,但是我一次可以做到这一点。

I am learning Powershell... 我正在学习Powershell ...

How can I save each worksheet from the workbook (excel 2010) to this format: file name + "-" + sheet name as CSV? 如何将工作簿(Excel 2010)中的每个工作表保存为以下格式:文件名+“-” +工作表名称为CSV?

  • I have up to 3 worksheets per workbook on some workbooks (might be more...) 在某些工作簿上,每个工作簿最多有3个工作表(可能更多...)
  • Is there is an optimal way of performing this? 有没有执行此操作的最佳方法?

Thank you, 谢谢,

$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);

I haven't tested it, but I think it should work. 我还没有测试过,但是我认为它应该可以工作。 I've explained the changes in the code: 我已经解释了代码中的更改:

$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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM