Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.
Sign upValidateScript does not work for class properties #12517
Comments
perhaps class is by design static scoping and scriptblock with validateScript is interpreted dynamically...maybe you can create your own attribute with class [System.Management.Automation.ValidateArgumentsAttribute] |
In this specific case you could use But yeah, classes are handled at parse time, so attributes have some extra restrictions. I'm not sure there's a way around that? Might be, but I would guess there probably isn't much that's really doable there. |
@vexx32 The simple example is just that - a simple example. My need for ValidateScript is obviously much more complex. Could you point me to the documentation where this is listed as expected behavior since you are not surprised about this behavior? I could not find many relevant matches doing a web search about validatescript and class but several did have other people wondering about ValidateScript and this problem. So it would not seem to be very well documented. It is disappointing. If class methods are not static like this then I might be able to figure out an ugly workaround if I have to. |
I'm mainly not surprised because I've seen it before, both in PS and (more importantly) in C# itself. In compiled code you can't have non-constant/non-primitive values for attributes. It's actually part of the attribute language specification which states:
I think there are similar underlying requirements for dynamically compiled assemblies, and .NET in the more general case as well. I'm pretty sure the only reason Classes in PS are a different story entirely, and have to be compiled as-is at parse time, meaning there's no deferred compilation or special handling of attributes for the most part, they just behave very much like C# / .NET attributes. As far as documenting it in PowerShell, I'd tend to agree that it should be mentioned somewhere in the classes documentation. |
/cc @rjmholt |
Yeah @vexx32 has hit it on the head. It looks like we should handle this more gracefully. I imagine that this is "expected if you think about the implementation and extrapolate", but has not been anticipated by the existing implementation. Currently classes are compiled into dynamic .NET assemblies, and won't tolerate attributes that do something that .NET doesn't like, namely use values that can't be embedded into .NET static metadata. I don't see I think we should:
|
Steps to reproduce
Output:
Output:
Expected behavior
It should be possible to use ValidateScript in classes the same way as for function parameters.
If there is a technical limitation why the behavior is expected then it should be documented somewhere - I could not find anything in documentation about this.
Actual behavior
All validations except ValidateScript work as expected in classes.
Environment data