Am trying to automate certain tasks that I have to do, that although simple are tedious, due to the number of files. I currently have a script that will refresh every file within a folder, now these files have more worksheets that what my client needs, so after refreshing, I need to copy/paste the first two sheets in a new workbook, save in a general location where the client pick's it up. I have added what I thought was good code to do this copy/paste, but unfortunately, I'm getting errors in the copy/paste section as well as the SaveAs part. I did some research here and at "powershell.org", but couldn't find anything that helped :(.
This is my code:
Measure-Command {
$excel = new-object -comobject excel.application
$excel.DisplayAlerts = $false
$excelFiles = Get-ChildItem -Path "Network folder location" -Include *.xls, *.xlsm,*.xlsx, *.lnk -Recurse
Foreach($file in $excelFiles) {
$workbook = $excel.workbooks.open($file.fullname)
foreach ($Conn in $workbook.Connections){
$Conn.OLEDBConnection.BackgroundQuery = $false
$Conn.refresh()
}
$workBook.RefreshAll()
$workbook.save()
$wb2 = $excel.Workbooks.Add()
$sheetToCopy = $workbook.sheets.item(1),$workbook.sheets.item(2) #Source
$sheetToCopy.CopyTo($wb2) #Destination
$filename = $wb2.Sheets.Item(2).Cells.Item(4,2) #Destination file, 2nd sheet, column D row 2 has what I want to call the file (RVP John Doe - Dashboard)
$wb2.SavesAs("Networkfolder\$filename.xlsx")
$workbook.close()
$wb2.close()
}
$excel.quit()
}