Skip to content

Instantly share code, notes, and snippets.

@ritalin
Last active November 18, 2016 06:42
Show Gist options
  • Save ritalin/965322b769167b3b36dab7d50d0fd3cb to your computer and use it in GitHub Desktop.
Save ritalin/965322b769167b3b36dab7d50d0fd3cb to your computer and use it in GitHub Desktop.
A function boilerplate for Excel processing by powershell.
function BoilerplateFunction {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[IO.FileInfo[]]$files
)
begin {
$xls = New-Object -ComObject Excel.Application
$xls.Visible = $false
$xls.DisplayAlerts = $false
$books = $xls.WorkBooks
function Cleanup {
CleanupObjects @($xls, $books)
}
}
process {
try {
foreach ($f in $files) {
}
}
catch {
Cleanup
throw
}
}
end {
Cleanup
}
}
function CleanupObjects($objects) {
foreach ($obj in $objects) {
[Runtime.InteropServices.Marshal]::FinalReleaseComObject($obj) | Out-Null
}
}
function BoilerplateFunctionInternal($books, [IO.FileInfo]$file) {
$book = $books.Open($file.FullName)
$sheets = $book.Sheets
$sheet = $sheets.Item(1)
$cells = $sheet.Cells
try {
SomeProcess $cells
}
finally {
$book.Close();
CleanupObjects @($cells, $sheet, $sheets)
}
}
function SomeProcess($cells) {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment