Reputation: 14705
I've written an advanced function that does stuff with the input $Text
and the information coming from an Excel file. The function itself is pretty fast, only the part for reading the Excel file (Import-ExcelHC
) is slow and needs some time.
This function has been made available within a module. Now every time I call this function, it needs to read the Excel file, which is normal. But the Excel file doesn't change that often, so I don't really need to read it every single time I call the function.
Is it possible to only have the Excel file read once when the module is loaded? So the function doesn't need to read the Excel file every time I call it from within a script?
I'm sorry if this seems like a noob question, but I'm new to using modules. Thank you for your help.
MyModule.PSM1:
Function Foo ($Text) {
Begin {
$Excel = Import-ExcelHC -File 'C\Test.xlsx' # slow part
}
Process {
Write-Host "We did some stuff with $Text and $Excel"
}
}
Thank you for your help.
Upvotes: 1
Views: 174
Reputation: 1781
Another thought: You could also have it check the LastWriteTime property on loading the module, then in your function have it compare it to what it was when the module was loaded to make sure you're working with the latest version. This way you only reload it if it's been updated.
On module load:
$excelwritetimeonload = (Get-Childitem 'C:\Test.xlsx').lastwritetime
Then inside the function:
$excelwritetimecurrent = (Get-Childitem 'C:\Test.xlsx').lastwritetime
if ($excelwritetimecurrent -gt $excelwritetimeonload) {
$Excel = Import-ExcelHC -File 'C:\Test.xlsx' # slow part
}
Upvotes: 1
Reputation: 18156
You can include the
$Excel = Import-ExcelHC -File 'C\Test.xlsx' # slow part
at the end of the module outside of any functions. Code outside of functions is executed when you load a module.
Upvotes: 1