Submitted By: Kent Finkle

Opens an existing Excel spreadsheet, makes some changes, and then re-saves the file.

PowerShell
Edit|Remove
$comments = @'
Script name: ReSave-Excel.ps1
Created on: Friday, April 13, 2007
Author: Kent Finkle
Purpose: How can I use Windows Powershell to Make Changes to and Then Re-Save an Existing Excel Spreadsheet?
'@

# -----------------------------------------------------
function Release-Ref ($ref) {
([System.Runtime.InteropServices.Marshal]::ReleaseComObject(
[System.__ComObject]$ref) -gt 0)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
# -----------------------------------------------------

$objExcel = new-object -comobject excel.application 
$objExcel.Visible = $True 
$objExcel.DisplayAlerts = $False

$objWorkbook = $objExcel.Workbooks.Open("C:\Scripts\Test.xls")
$objWorksheet = $objWorkbook.Worksheets.Item(1)

$objWorksheet.Cells.Item(1, 1) = get-date
$objWorkbook.SaveAs("C:\Scripts\Test.xls")
$objExcel.Quit()

$a = Release-Ref($objWorksheet)
$a = Release-Ref($objWorkbook)
$a = Release-Ref($objExcel)