Welcome to MSDN Blogs Sign in | Join | Help

Tied Variables in PowerShell

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]

Published Thursday, March 26, 2009 11:17 PM by PowerShellTeam
Filed under: , ,

Attachment(s): New-ScriptVariable.ps1.txt

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# infoblog » Tied Variables in PowerShell

Thursday, March 26, 2009 6:39 PM by infoblog » Tied Variables in PowerShell

# re: Tied Variables in PowerShell

Dude!  I have been looking for how to do just this.  I figured out a way to do string based variables, but this is so much more powerful.  Thank you for adding such great features.

Thursday, March 26, 2009 7:06 PM by JasonMArcher

# Many² ways you can set a variable value

There are many ways to set a variable's value. I just learnt one more yesterday. If you have others,

Thursday, April 02, 2009 5:16 PM by Windows PowerShell Blog

# Many² ways you can set a variable value

There are many ways to set a variable's value. I just learnt one more yesterday. If you have others

Thursday, April 02, 2009 10:46 PM by PowerShell Team Blog (external)

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker