6

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
1
  • Problem is, PSObjects are designed for use in PowerShell scripting. Classes are more designed for use in programming. The ability to create a class is helpful, there have been a few cases I have wanted to do this myself for a specific reason (such as strict object requirements and typing), but it's most likely the .NET classes which are for programming so I'd be surprised if you can add script properties... Commented Aug 24, 2016 at 13:33

1 Answer 1

0

not sure I understand the problem here. This is how I create, extend and access custom objects; let me know if you're after something else.

# Creating new object with key/value hashtable
$customObject = New-Object psobject -Property @{key1 = "value" ; key2 = "value2"}

# Adding member to custom object
$customObject | Add-Member -MemberType NoteProperty -Name key3 -Value value3

# This will return value3
$customObject.key3

========================================================================

Edit - I'm not familiar with classes. In PowerShell 5 it is possible to extend custom objects with a ScriptProperty member and specify a scriptblock that is calculated on the go (no hackery required).

$test = New-Object psobject
$test | Add-Member -Name currentime -MemberType ScriptProperty -Value {Get-Date}
$test.currentime

It is possible to specify a -SecondValue scriptblock that handles setting the property (keep running into StackOverflowException when testing this)

1
  • I want to use classes, that's the whole point. That's much more robust and easy to read and maintain. But I cannot find a way to emulate the trickiest membertypes of Add-Member. Commented Aug 24, 2016 at 15:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.