Skip to content

Instantly share code, notes, and snippets.

@FriedrichWeinmann
Last active June 11, 2019 04:30
Show Gist options
  • Save FriedrichWeinmann/2d224f8e43942daa895192e22aaa8d6d to your computer and use it in GitHub Desktop.
Save FriedrichWeinmann/2d224f8e43942daa895192e22aaa8d6d to your computer and use it in GitHub Desktop.
Adds caching to Out-Default
function Out-Default
{
<#
.SYNOPSIS
A wrapper for Out-Default, adding automatic caching to all output sent to screen.
.DESCRIPTION
A wrapper for Out-Default, adding automatic caching to all output sent to screen.
Maximum capacity can be configured by setting $global:OutputCacheSize
Data can be accessed by inspecting $global:OutputCache
.PARAMETER InputObject
The data to cache and display
.EXAMPLE
PS C:\> Get-ChildItem
The contents of the current folder are displayed ... and cached to $global:OutputCache
#>
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline = $true)]
$InputObject
)
begin
{
if (-not $global:OutputCacheSize) { $global:OutputCacheSize = 10 }
if (-not $global:OutputCache) { $global:OutputCache = New-Object 'System.Collections.Generic.Queue[Object]' }
$data = New-Object 'System.Collections.Generic.List[Object]'
#region Wrap Out-Default Cmdlet
try
{
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Out-Default', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = { & $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline()
$steppablePipeline.Begin($PSCmdlet)
}
catch
{
throw
}
#endregion Wrap Out-Default Cmdlet
}
process
{
$data.Add($InputObject)
#region Wrap Out-Default Cmdlet
try
{
$steppablePipeline.Process($_)
}
catch
{
throw
}
#endregion Wrap Out-Default Cmdlet
}
end
{
if ($data.Count -gt 0)
{
$global:OutputCache.Enqueue($data.ToArray())
while ($global:OutputCache.Count -gt $global:OutputCacheSize)
{
$null = $global:OutputCache.Dequeue()
}
}
#region Wrap Out-Default Cmdlet
try
{
$steppablePipeline.End()
}
catch
{
throw
}
#endregion Wrap Out-Default Cmdlet
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment