pf-caching.ps1
function Clear-PSCache ($region) { $regionCache = Get-Variable -Name $region -Scope global -ErrorAction Continue if ($regionCache) { Remove-Variable -Name $region -Scope global } } function Get-PSCache ($region, $key, [ScriptBlock]$genValue) { $regionCache = Get-Variable -Scope global | Where-Object Name -eq $region if (-not $regionCache) { $regionCache = @{} Set-Variable -Name $region -Scope global -Value $regionCache } else { $regionCache = $regionCache.Value } if ($regionCache.Contains($key)) { $result = $regionCache[$key] if ($result) { return $result } } $result = Invoke-Command -ScriptBlock $genValue -ArgumentList @{region = $region; key = $key} if ($result) { $regionCache[$key] = $result } return $result } function Get-PSCache:::Test { $region = 'CacheTest' $key = 'Key1' Clear-PSCache -region $region Get-PSCache -region $region -key $key -genValue { $args[0].key } | Assert $key Get-PSCache -region $region -key $key -genValue { $args[0].key + '_NoExpected' } | Assert $key Clear-PSCache -region $region Get-PSCache -region $region -key $key -genValue { $args[0].key + '_2' } | Assert ( $key + '_2') Clear-PSCache -region $region } |