EDITED to reduce confusion on the intended aim
Is it possible to create any sort of annotation which can apply a common pattern to a function?
An example may be a standard error-handling routine. Rather than having to implement the same try/catch structure with the error-handling function, it would be nice to have an attribute or annotation with which I could decorate the function, thus implementing the common pattern without using the same explicit code in each function.
Perhaps this is a case of trying to shoehorn PowerShell into doing something it isn't meant to do, but I'd like to avoid some of the repetition I find most common in my scripts.
You just need to inherit from ValidateArgumentsAttribute
class and provide custom validation logic in Validate
method:
C#:
Add-Type @‘
using System;
using System.Management.Automation;
public class ValidateIsEvenAttribute : ValidateArgumentsAttribute {
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) {
if(LanguagePrimitives.ConvertTo<int>(arguments)%2==1) {
throw new Exception("Not even");
}
}
}
’@
PowerShell v5:
class ValidateIsOddAttribute : Management.Automation.ValidateArgumentsAttribute {
[void] Validate([object] $arguments, [Management.Automation.EngineIntrinsics] $engineIntrinsics) {
if($arguments%2-eq0) {
throw 'Not odd'
}
}
}
Then you can apply that attributes to function parameters:
function f { param([ValidateIsEven()]$i, [ValidateIsOdd()] $j) $i, $j }
f 2 1 #OK
f 2 2 #Error
f 1 1 #Error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With