【问题标题】:How do I create and use a custom function attribute in PowerShell?如何在 PowerShell 中创建和使用自定义函数属性?
【发布时间】:2017-01-07 19:28:15
【问题描述】:

我希望能够创建自定义属性并将其分配给我的 powershell 函数。我到处看了看,似乎有可能,但我没有看到一个例子。我在 C# 中创建了一个自定义属性,并在我的 powershell 脚本中引用了该程序集。但是,我收到一条错误消息,指出 Unexpected attribute 'MyDll.MyCustom'.

这是我所拥有的:

MyDll.dll 中的 MyCustomAttribute:

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 脚本:

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

    # Do stuff 
}

然而,值得注意的是,如果我这样做:

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

它工作正常。所以类型显然被正确加载。我在这里错过了什么?

【问题讨论】:

    标签: function powershell custom-attributes


    【解决方案1】:

    看起来你需要改变两件事:

    1. 命令属性需要在语法上位于 param() 块之前。
    2. 使用 Name = 说明符似乎会导致 PowerShell 解析器将属性参数视为初始值设定项,此时构造函数将无法解析。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-20
      • 2011-10-23
      • 1970-01-01
      • 2019-01-08
      • 1970-01-01
      • 2022-06-12
      • 1970-01-01
      • 2014-09-16
      相关资源
      最近更新 更多