Tied Variables in PowerShell

PowerShell Team

With Add-Type and $executioncontext you can add special varibles that have tied values.

I made $random, and $now

add-type @”
using System;
using System.Management.Automation;
public class RandomVariable : PSVariable
{
Random r;
public RandomVariable ()
  : base(“Random”, 0, ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope)
  {r = new Random();}

     public override object Value
        {
            get
            {
            return  r.Next();
            }
        }
}
“@
$executioncontext.SessionState.PSVariable.Set((new-object RandomVariable))

add-type @”
using System;
using System.Management.Automation;
public class NowVariable : PSVariable
{
public NowVariable ()
  : base(“Now”, 0, ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope)
  {}
       public override object Value
        {
            get
            {
            return  DateTime.Now;
            }
        }
}
“@
$executioncontext.SessionState.PSVariable.Set((new-object NowVariable))

Results is,
PS C:\tmp> $Random
229309908
PS C:\tmp> $Random
1759972224
PS C:\tmp> $Now
Thursday, 26 March 2009 3:20:29 PM

I got this from Lee, where you can bind the behaviour to ScriptBlocks instead of C#, making it even easier to use. See attached

 It has in it,
            get
            {
                if(getter != null) { return getter.Invoke(); }
                else { return null; }
            }

Which is a simple way to cross over to PowerShell from C#
And you can use it like so,
PS C:\temp> New-ScriptVariable.ps1 GLOBAL:today { (Get-Date).DayOfWeek }
PS C:\temp> $today
Wednesday

Cheers,
Ibrahim Abdul Rahim [MSFT]

New-ScriptVariable.ps1.txt

0 comments

Discussion is closed.

Feedback usabilla icon