In Powershell versions prior to 5, objects could be created "on the go" with New-Object, and could be extended with Add-Member. Powershell 5 introduced classes, but it seems they only allow basic properties and methods. Is there any proper way one can emulate a scriptproperty (IE. a property that is seen as a property, not as a method, but is still calculated on the go)?
The following code gives the wanted result thanks to a hack in the constructor. Can this hack be avoided?
class fakescriptproperty {
hidden [datetime] _currenttime() { return ( Get-Date ) }
fakescriptproperty() {
Add-Member -InputObject $this -MemberType ScriptProperty `
-Name currenttime -Value { $this._currenttime() }
}
}
$test = New-Object -TypeName fakescriptproperty
$test.currenttime