Skip to content

Instantly share code, notes, and snippets.

@jstangroome
Created August 30, 2012 04:48
Show Gist options
  • Save jstangroome/3522474 to your computer and use it in GitHub Desktop.
Save jstangroome/3522474 to your computer and use it in GitHub Desktop.
Cmdlet to add lazy evaluated properties to PowerShell objects
function Add-LazyProperty {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[PSObject]
$InputObject,
[Parameter(Mandatory=$true, Position=1)]
[string]
$Name,
[Parameter(Mandatory=$true, Position=2)]
[ScriptBlock]
$Value,
[switch]
$PassThru
)
process {
$LazyValue = {
$Result = & $Value
Add-Member -InputObject $this -MemberType NoteProperty -Name $Name -Value $Result -Force
$Result
}.GetNewClosure()
Add-Member -InputObject $InputObject -MemberType ScriptProperty -Name $Name -Value $LazyValue -PassThru:$PassThru
}
}
function Test-LazyProperty {
# get a boring object
$TestObject = Get-Process -Id $PID
# make sure it's a PSObject, this step is unnecessary in PowerShell v3
$TestObject = [PSObject]$TestObject
# add a script property to return the current ticks
$TestObject | Add-Member -MemberType ScriptProperty -Name Ticks -Value { (Get-Date).Ticks }
# add a lazy property to return the current ticks
$TestObject | Add-LazyProperty -Name LazyTicks -Value { (Get-Date).Ticks }
# display the property members, notice they are both ScriptProperties
$TestObject | Get-Member -Name *Ticks
# display the property values once
$TestObject | Select-Object -Property *Ticks
# display the property members, notice LazyTicks is now a static NoteProperty
$TestObject | Get-Member -Name *Ticks
# display the property values again, notice LazyTicks hasn't changed
$TestObject | Select-Object -Property *Ticks
}
Test-LazyProperty
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment