Using Powershell to loop through Excel files and check if Spreadsheet name exists

后端 未结 2 532
情话喂你
情话喂你 2021-01-19 05:09

I\'m trying to write a powershell script that will loop through each excel file in the given directory, check the file for a specifically named worksheet, and then copy that

相关标签:
2条回答
  • 2021-01-19 05:55

    You don't need this line:

    [void][reflection.assembly]::Loadwithpartialname("microsoft.office.excel")
    

    ($Excel = New-Object -ComObject Excel.Application is sufficient here)

    I don't think you're referencing the full path to your Excel files. Try modifying this line:

    $WorkBook = $Excel.Workbooks.Open($file)
    

    Amend to:

    $WorkBook = $Excel.Workbooks.Open($file.Fullname)
    

    Additionally, consider adding a filter to your Get-ChildItem command, if there are sub-directories or non-Excel files, they will cause errors:

    $files = Get-ChildItem C:\Test -filter "*.xls"
    
    0 讨论(0)
  • 2021-01-19 06:12

    There were several issues with my script's logic. The following script ran successfully! It took hours of research...

    $ErrorActionPreference= 'silentlycontinue'
    $tempLocation = "C:\Source"     # Path to read files
    $targetlocation = "C:\Target"
    Write "Loading Files..."
    $files = Get-ChildItem C:\Source
    Write "Files Loaded."
    ForEach ($file in $files)
    {
    #Check for Worksheet named TestSheet
         $Excel = New-Object -ComObject Excel.Application
         $Excel.visible = $false
         $Excel.DisplayAlerts = $false
         $WorkBook = $Excel.Workbooks.Open($file.Fullname)
         $WorkSheets = $WorkBook.WorkSheets | where {$_.name -eq "TestSheet"}
    
         if($WorkSheets) {
         $path = $tempLocation + "\" + $file
         $dest = $targetlocation + "\" + $file
         Write "Saving $path"
         $WorkBook.SaveAs($dest)
         }
         $Excel.Quit()
         Stop-Process -processname EXCEL
    }
    Read-host -prompt "The Scan has completed.  Press ENTER to close..."
    clear-host;
    
    0 讨论(0)
提交回复
热议问题