1

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.

2 Answers 2

1

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
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Very good suggestion this one! Although, one should not forget to still do an initial call on the slow function when loading the module.
1

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.

1 Comment

Fully awesome! I didn't know this was possible. It's a real time saver for me :) Thank you very much Mike!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.