PowerTip: Create Self-Updating Variable


Summary: Learn how to create a self-updating variable.

Hey, Scripting Guy! Question How can I create a variable that will automatically update when I call it?

Hey, Scripting Guy! Answer Use Set-PSBreakPoint to set a variable that will always have the current date and time (or only time):

Set-PSBreakpoint -Variable Time -Mode Read -Action {$Global:Time=(Get-Date).ToShortTimeString();$Global:Time}

$Time

Set-PSBreakpoint -Variable Date -Mode Read -Action {$Global:Date=Get-Date;$Global:Date}

$Date

Note  You need to call the variable to kick off the PSBreakPoint action script block the first time.
           After that, the information will be up-to-date.

PS C:> $Date

Wednesday, October 29, 2014 10:01:28 PM

PS C:> $Time

10:01 PM

Comments (6)

  1. Valeras says:

    will it work on remote machine also? as per set-psbreakpoint description i shouldn’t but it is cool, will use it to check output of not mine scripts to write all output in log file. thanks

  2. jrv says:

    Now that is cool.

  3. David Wyatt says:

    There’s another way of accomplishing this same effect, which doesn’t rely on breakpoints. With a little bit of embedded C#, you can create a subclass of PSVariable which returns a dynamic value. The PowerShell team posted a blog on this topic a while back:

    http://blogs.msdn.com/b/powershell/archive/2009/03/26/tied-variables-in-powershell.aspx
    http://www.leeholmes.com/blog/2009/03/

  4. Brandon says:

    Cool, but I wouldn’t suggest using this method in real code. In my opinion, It is confusing to a user reading the code, because this behavior is very atypical. I would rather create a function that is called each time, since this is essentially what you
    are doing.

    I’m sure you could also do a "-Mode Write" which ran a code block whenever a variable’s value is set?

  5. georgi ivanov says:

    Not sure if it is good idea, because every variable’s value is examined every time you type "$". Which can lead to substantial performance impact in some cases. I prefer creating script property of pscustomobject with getter and setter(need to refer variable’s
    prop off course). Also using new-module -ascustomobject and defining the paramer with $script scope will make it invisible outside of the pscustomobject(so it can store the actual value if needed). But all these will be available ot of the box with ps5 classes
    🙂

Skip to main content