我可以使用自己的自定义属性来装饰高级PowerShell函数吗?

tel*_*ine 6 powershell attributes function

例如:

function TestThis()
{
    [MySpecialCustomAttribute]
    [CmdletBinding()]
    Param(...)
    Process{...}

}
Run Code Online (Sandbox Code Playgroud)

Jay*_*kul 1

是的,当然可以!

任何派生Attribute自 allowed UsageType.All(或UsageType.Class) 的类型都可以在函数本身上使用(即上面的Param

任何派生Attribute允许UsageType.PropertyUsageType.Field使用的类型都可以用于参数本身或变量。

只是懒惰和使用的情况并不少见UsageType.All(例如内置OutputType属性就是这样做的)。

您现在甚至可以在 PowerShell 类中编写它们

using namespace System.Management.Automation
class ValidateFileExistsAttribute : ValidateArgumentsAttribute {
    [void] Validate([object]$arguments, [EngineIntrinsics]$engineIntrinsics) {
        if($null -eq $arguments) {
            throw [System.ArgumentNullException]::new()
        }
        if(-not (Test-Path -Path "$arguments" -Type Leaf)) {
            throw [System.IO.FileNotFoundException]::new("The specified path is not a file: '$arguments'")
        }        
    }
}
Run Code Online (Sandbox Code Playgroud)

Kevin Marquette的博客上查看更多示例。

这里有一个较旧的示例,展示了如何在 PowerShell 4 及更早版本中使用 Add-Type 执行此操作,尽管现在有点过时了,因为它显示的特定示例已集成到 PowerShell 6 中并且不再需要

还有视频

  • 链接已失效,请在此处包含解决方案 (3认同)