I was unable to work with more than one user attribute (decorator) in a PowerShell 5.0 class method. In C #, I can do the following:
public class SomeAttribute : Attribute {
public string Text { get; set; }
}
public class OtherAttribute : Attribute {
public string Text { get; set; }
}
public class MyClass {
[SomeAttribute(Text = "sometext")]
[OtherAttribute(Text = "othertext")]
public void MyMethod() {
}
}
and then call somewhere else
object[] customAttributes = typeof(MyClass).GetMethod("MyMethod").GetCustomAttributes(false);
which gives me an array of all the custom attributes associated with this method, without any problems.
In PowerShell 5.0, I am trying to use a similar way:
class SomeAttribute : Attribute {
[string]$Text
}
class OtherAttribute : Attribute {
[string]$Text
}
class MyClass {
[SomeAttribute(Text="sometext")]
[OtherAttribute(Text="othertext")]
MyMethod() {
# ...
}
}
which seems to be the correct syntax since PowerShell gladly accepts it. But listing attributes through
[MyClass].GetMethod("MyMethod").GetCustomAttributes($false)
returns the following error:
Exception calling "GetCustomAttributes" with "1" argument(s): "Could not load type 'OtherAttribute' from assembly '⧹powershell, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'."
At line:1 char:1
+ [MyClass].GetMethod("MyMethod").GetCustomAttributes($false)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : TypeLoadException
and
[MyClass].GetMethod("MyMethod").CustomAttributes
just returns $null.
, , , , .
PowerShell 5.0?
-
.
class SomeAttribute : Attribute {
[string]$Text
}
class MyClass {
[SomeAttribute(Text="sometext")]
MyMethod() {
# ...
}
}
[MyClass].GetMethod("MyMethod").GetCustomAttributes($false)
Text TypeId
---- ------
sometext SomeAttribute
[MyClass].GetMethod("MyMethod").CustomAttributes
AttributeType Constructor ConstructorArguments NamedArguments
------------- ----------- -------------------- --------------
SomeAttribute Void .ctor() {} {Text = "sometext"}
, , .