PoshCode Logo PowerShell Code Repository

New-TiedVariable by Joel Bennett 34 months ago
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/2750"></script>download | new post

A function for creating tied variables using Robert Robelo’s idea to create breakpoints that update the variable values.

  1. function New-TiedVariable {
  2. #.Synopsis
  3. #   Creates a ReadOnly variable that recalculates it's value each time it's read
  4. #.Description
  5. #   Create a variable tied to a scriptblock by using a breakpoint ;-)
  6. #.Notes
  7. #   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
  8. param(
  9.     # The name of the variable to create
  10.     [String]$Name,
  11.     # The scriptblock to use to calculate the value each time
  12.     [ScriptBlock]$Value
  13. )
  14.     Set-Variable $Name -Value (.$Value) -Option ReadOnly, AllScope -Scope Global -Force
  16.     $null = Set-PSBreakpoint -Variable $Name -Mode Read -Action {
  17.         Set-Variable $Name (. $Value) -Option ReadOnly, AllScope -Scope Global -Force
  18.     }.GetNewClosure()
  19. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:

Remember me