动态的PowerShell项
在对增强请求 #27023 的扩展中,我试图创建一个原型,基本上相当于是一个动态的项,而不是一个动态的变量(如 latkin 的 这个回答 中所述)。
因此,不再是 $Now 变量,而是一个 $PS:Now 项:
$null = New-PSDrive -Name PS -PSProvider Environment -Root \
$null = New-Item -Path PS: -Name Now -Value ([DateTime]::Now)
$PS:Now
Start-Sleep -Seconds 1
$PS:Now
其中我希望每次被调用时,$PS:Now 的响应都能向前推进。
问题在于,据我所知,目前没有办法在一个 PSDrive 项上设置断点;另一方面,如果一个 PSDrive 项具备实现这一目标的其他特性,我也不会感到惊讶。
有什么办法让一个 PSDrive 项变成动态的吗?
解决方案
Edit: See mklements reply where the New-PSDrive for a Variable provider doesn't actually namespace the variables. They will still be available in the normal Variable PSDrive so it's useless to do. For this task you really should look at a custom PSProvider implementation that can natively do this.
虽然强烈不推荐你这么做,但 PSVariable类 并不是sealed的,因此你可以定义一个Variable PSDrive和一个自定义 PSVariable 实现来override the Value getter。
class DynamicPSVariable : PSVariable {
[ScriptBlock]$_Getter
DynamicPSVariable([string]$Name, [ScriptBlock]$Getter) : base($Name) {
$this._Getter = $Getter
}
[object] get_Value() {
return & $this._Getter
}
[void] set_Value([object]$Value) {
throw "Cannot set a dynamic variable"
}
}
New-PSDrive -Name PS -PSProvider Variable -Root \
$dynamicNow = [DynamicPSVariable]::new('Now', { [DateTime]::Now })
New-Item -Path PS:Now -Value $dynamicNow | Out-Null
$PS:Now
Start-Sleep -Seconds 1
$PS:Now
使用的 Variable 提供程序的额外好处是,你不再编辑一个进程范围的设置,这将限定在你正在运行的Runspace中。
你甚至可以使用这个 DynamicPSVariable 类,在普通变量提供程序中设置一个“动态”的变量,从而让你可以做类似下面的事情
$dynamicNow = [DynamicPSVariable]::new('Now', { [DateTime]::Now })
New-Item -Path Variable:Now -Value $dynamicNow
$Now
Start-Sleep -Seconds 1
$Now