Last active
September 8, 2022 14:09
-
-
Save OtterKring/9834354759927341a8b0fc9639c7acea to your computer and use it in GitHub Desktop.
This file contains 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
### all this goes into the begin {} block of a cmdlet | |
# check and/or set function cache | |
# scope must be global to remain in memory until the function is called again | |
# variable will be names "cache_" + name of the function | |
# initial value will be an empty hashtable, so you can add data nodes as needed in your function | |
$CacheName = "cache_$($MyInvocation.InvocationName)" | |
if ( -not ( Get-Variable -Name $CacheName -Scope global -ErrorAction SilentlyContinue ) ) { | |
New-Variable -Name $CacheName -Value @{} -Scope global | |
} | |
# for ease of use reference the hashtable to a local variable | |
# since referenced and not copied, all changes to the local variable will | |
# be replicated in the global cache variable | |
$Cache = (Get-Variable -Name $CacheName).Value | |
### usage example | |
# load data to cache if not there | |
# HERE IS THE PERFORMANCE GAIN: if the data is already there, you don't need to | |
# fetch it from the remote system! | |
if ( -not $Cache.AcceptedDomains ) { | |
$Cache.AcceptedDomains = ( Get-AcceptedDomain ).DomainName | Sort-Object | |
} | |
function isAcceptedDomain ( [System.Net.Mail.MailAddress]$SmtpAddress ) { | |
[array]::BinarySearch($Cache.AcceptedDomains, $SmtpAddress.Host) -ge 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment