Creating Dynamic Variable Content

by Aug 15, 2016

PowerShell 2+

A little-known fact is that you can add variables to PowerShell that automatically update their content. If you need random numbers, for example, this code would add a new variable called $Random that provides a new random number each time it is called:

Add-Type 'using System;
using System.Management.Automation
public class FixedVariableRandom : PSVariable
{
Random 
public FixedVariableRandom()
  : base("Random", 0, ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope)
  {r = new Random()}

  public override object Value
  {
    get { return  r.Next() }
  }
}'

$ExecutionContext.SessionState.PSVariable.Set((New-Object FixedVariableRandom))

Likewise, this example creates a variable named $Now which 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))

Twitter This Tip! ReTweet this Tip!