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> $Random229309908PS C:\tmp> $Random1759972224PS C:\tmp> $NowThursday, 26 March 2009 3:20:29 PMI 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> $todayWednesday
Cheers,Ibrahim Abdul Rahim [MSFT]