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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With