How to create and use a custom function attribute in PowerShell?

I want to be able to create and assign a custom attribute for my powershell functions. I looked everywhere and it seems possible, but I did not see an example. I created a custom attribute in C # and reference the assembly in my powershell script. However, I get an errorUnexpected attribute 'MyDll.MyCustom'.

Here is what I have:

MyCustomAttribute in MyDll.dll:

namespace MyDll
{
    [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
    public sealed class MyCustomAttribute : Attribute
    {
        public MyCustomAttribute(String Name)
        {
            this.Name= Name;
        }

        public string Name { get; private set; }
    }
}

PowerShell Script:

Add-Type -Path "./MyDll.dll";
function foo {
    [MyDll.MyCustom(Name = "This is a good function")]

    # Do stuff 
}

It should be noted, however, that if I do this:

$x = New-Object -TypeName "MyDll.MyCustomAttribute" -ArgumentList "Hello"

It works great. Thus, the type explicitly loads correctly. What am I missing here?

+4
source share
1 answer

It seems that two things need to be changed:

  • param().
  • Name =, -, , PowerShell , .

function foo {
    [MyDll.MyCustom("This is a good function")]
    param()
    # Do stuff 
}
+2

Source: https://habr.com/ru/post/1666103/


All Articles