PoshCode Archive  Artifact [cbd64ff4ff]

Artifact cbd64ff4ff92f6413e3bbfe39e8392774fd2d993bcb02e56585b9f598ded1a5d:

  • File New-TiedVariable.ps1 — part of check-in [e8b1c89c4e] at 2018-06-10 13:15:14 on branch trunk — A function for creating tied variables using Robert Robelo’s idea to create breakpoints that update the variable values. (user: Joel Bennett size: 1278)

# encoding: ascii
# api: powershell
# title: New-TiedVariable
# description: A function for creating tied variables using Robert Robelo’s idea to create breakpoints that update the variable values.
# version: 0.1
# type: function
# author: Joel Bennett
# license: CC0
# function: New-TiedVariable
# x-poshcode-id: 2750
# x-archived: 2011-11-17T12:31:34
# x-published: 2011-06-24T16:31:00
#
#
function New-TiedVariable {
#.Synopsis
#   Creates a ReadOnly variable that recalculates it's value each time it's read
#.Description
#   Create a variable tied to a scriptblock by using a breakpoint ;-)
#.Notes
#   New-TiedVariable uses breakpoints to trigger the automatic recalculation of the variables, so the use of a command like Get-PSBreakPoint | Remove-PSBreakPoint will break any variables created using New-TiedVariable
param(
    # The name of the variable to create
    [String]$Name,
    # The scriptblock to use to calculate the value each time
    [ScriptBlock]$Value
)
    Set-Variable $Name -Value (.$Value) -Option ReadOnly, AllScope -Scope Global -Force

    $null = Set-PSBreakpoint -Variable $Name -Mode Read -Action {
        Set-Variable $Name (. $Value) -Option ReadOnly, AllScope -Scope Global -Force
    }.GetNewClosure()
}