Most of the time when some part of a script takes a long time to run and you want to re-use the result you’ll store it in a variable:
$databases = Get-ListOfDatabases # assume this is an expensive/long-running query Invoke-SomeOperation -Server serverOne -Databases $databases Invoke-SomeOtherOperation -Server serverOne -Databases $databases
As long as the function you’re calling allows you to pass in the ‘expensive’ argument you’re fine - but what about cases when the computation takes place inside the function:
Invoke-SomeOperation -Server serverOne # internally calls Get-ListOfDatabases Invoke-SomeOtherOperation -Server serverOne # internally calls Get-ListOfDatabases
Sometimes it makes sense to rework the script to accept the argument, though other times it can be cleaner to modify the call site to cache the result, rather than changing every function to accept and potentially pass through that argument.
The rest of this post will go through a specific example that motivated caching, share a generic function that implements scriptblock-based caching, and call out a few and gotchas.[Read More]