Created
August 30, 2012 04:48
-
-
Save jstangroome/3522474 to your computer and use it in GitHub Desktop.
Cmdlet to add lazy evaluated properties to PowerShell objects
This file contains hidden or 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
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