Wednesday, October 18, 2017

PowerShell script properties cannot be parameterized

PowerShell classes don't support properties with getter/setter methods, but Add-Member can add script properties with script-bodied getter and setter methods. Unfortunately, there isn't a way for these properties to take parameters like properties can in VB.NET, nor can the custom object be indexed like in C#. I did some poking around in the PowerShell source and determined that these downfalls cannot be worked around - arguments are never passed to the getter and setter, other than the current object (scriptThis) and the new value to the setter, of course.

The only workaround that I know of is to use Add-Type to generate a class from C# or VB.NET code. PowerShell script can then index the object with the normal bracket syntax, or use indexed properties with parentheses, almost like calling a method.

No comments:

Post a Comment