4

I want to be able to create and assign a custom attribute to my powershell functions. I looked everywhere and it seems to be possible but I have not seen an example. I have created a custom attribute in C# and am referencing the assembly in my powershell script. However, I receive an error stating Unexpected 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 
}

Of note, however, is that if I do this:

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

It works fine. So the type is clearly being loaded correctly. What am I missing here?

1 Answer 1

2

Seemingly two things you need to change:

  1. Command attributes need to syntactically precede the param() block.
  2. Using the Name = specifier seems to cause the PowerShell parser to treat the attribute argument as an initializer, at which point the constructor won't get resolved.

function foo {
    [MyDll.MyCustom("This is a good function")]
    param()
    # Do stuff 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.