是否可以创建我自己的“自动变量"?
我本质上想创建一个每次都会执行的变量.举个最简单的例子:
I essentially want to create a variable that would be executed every time. For the simplest example:
$myvar = `write-host foo`;
然后每次我引用 $myvar 时,它都会输出 foo:
Then everytime I referenced $myvar, it would output foo:
dir $myvar
Directory of foo:
重点是每次引用 $myvar 时都会重新执行 write-host foo
部分
The point being that the write-host foo
portion would be re-executed everytime I reference $myvar
通过创建您自己的 PSVariable 派生类,在托管代码 (C#/VB) 中是可行的,但不能直接在纯脚本中使用,抱歉.我说纯脚本"是因为在 powershell v2 中,您可以使用 add-type 内联 C#.也就是说,您可以通过依赖隐式 ToString 调用在脚本中破解它,但这在每种情况下都不可靠.示例:
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
希望能帮到你
-Oisin