Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock PowerShell V3 attributes in V2

Tags:

Being one who likes to document thoroughly, I was glad to discover the SupportsWildcards attribute, among others, added in PowerShell V3. I have decorated parameters in my library with that attribute as appropriate. In the long run there is no issue, but in the short term there are still plenty of folks using V2 for various reasons (including me in one environment).

It seems silly that just because of one attribute some of my functions can no longer run in PowerShell V2. So I am looking for a way to mock the attribute in V2 to essentially turn it into a "no-op".

The solution, as I see it, needs two parts:

  1. create an essentially empty custom attribute.
  2. make this take effect in V2 but be ignored in V3 (and hence allow the true V3 attribute to work properly).

I am looking for guidance on both parts, having not played with custom attributes before.

like image 499
Michael Sorens Avatar asked Mar 01 '13 16:03

Michael Sorens


1 Answers

Perhaps you can try this.

    Add-Type @"             public class CustomAttribute : System.Attribute         {            public bool SupportSomething { get; set; }          }     "@      function Do-Something {         param(             [CustomAttribute(SupportSomething=$true)]             $Command         )     }      $parameters = Get-Command -Name Do-Something | Select-Object -ExpandProperty Parameters     $parameters["Command"].Attributes 

Then the output:

    SupportSomething : True     TypeId           : CustomAttribute 

We first define the attribute in C#, which you can also do in PowerShell. Add the attribute to the parameter. Then get the list of attributes. See here for more attribute examples

like image 150
Coding101 Avatar answered Sep 28 '22 09:09

Coding101