Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PowerShell provide a way to create function annotations?

Tags:

powershell

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.

like image 254
Miles Grimes Avatar asked Dec 30 '16 15:12

Miles Grimes


1 Answers

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
like image 110
user4003407 Avatar answered Nov 06 '22 01:11

user4003407