Last active
November 18, 2016 06:42
-
-
Save ritalin/965322b769167b3b36dab7d50d0fd3cb to your computer and use it in GitHub Desktop.
A function boilerplate for Excel processing by powershell.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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