Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create my own 'automatic variable'?

Tags:

powershell

I essentially want to create a variable that would be executed every time. For the simplest example:

$myvar = `write-host foo`;

Then everytime I referenced $myvar, it would output foo:

dir $myvar

Directory of foo:

The point being that the write-host foo portion would be re-executed everytime I reference $myvar

like image 503
esac Avatar asked Nov 17 '10 20:11

esac


1 Answers

It's doable in managed code (C#/VB) by creating your own PSVariable derived class, but not directly in pure script, sorry. I say "pure script" because in powershell v2 you could inline the C# with add-type. That said, you could hack it in script by relying on implicit ToString calls but this would not be reliable in every situation. Example:

# empty custom object
$o = new-object psobject

# override ToString with a PSScriptMethod member
$o.psobject.members.add((new-object `
     System.Management.Automation.PSScriptMethod "ToString", {
         "ticks: $([datetime]::now.ticks)" }))

ps> $o
ticks: 634256043148813794

ps> $o
ticks: 634256043165574752

Note the tick count is different on each evaluation of the variable. If of course if you just use a regular function instead of a variable, this is much easier.

function Ticks { [datetime]::now.ticks }

# use as a parameter - note the use of ( and )
ps> write-host (ticks)
634256043148813794

# use in a string - note the use of $( and )
ps> write-host "ticks $(ticks)"
ticks 634256043165574752

Hope this helps

-Oisin

like image 63
x0n Avatar answered Sep 30 '22 13:09

x0n