Home QuickTipps Creating Magic Variables

Creating Magic Variables

Here is an example how you can add a dynamic variable to PowerShell. The code below creates a new variable named $now that always returns the current date and time:

Add-Type 'using System;
using System.Management.Automation;
public class FixedVariableNow : PSVariable
  public FixedVariableNow() : base("Now", 0, ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope)

  public override object Value
   get { return DateTime.Now; }

$ExecutionContext.SessionState.PSVariable.Set((new-object FixedVariableNow))

So here is what happens when you query $now:

PS C:\Users\tobwe> $Now

Wednesday, September 21, 2016 2:08:48 PM

PS C:\Users\tobwe> $Now

Wednesday, September 21, 2016 2:14:07 PM

PS C:\Users\tobwe> $now

Wednesday, September 21, 2016 2:14:11 PM

PS C:\Users\tobwe>

It auto-magically updates itself.