Automating the world one-liner at a time…
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]
PingBack from http://blog.a-foton.ru/index.php/2009/03/27/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.
There are many ways to set a variable's value. I just learnt one more yesterday. If you have others,
There are many ways to set a variable's value. I just learnt one more yesterday. If you have others
see also Robert Robelo's technique at
robertrobelo.wordpress.com/.../tied-variables-a-simpler-way