Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I decorate advanced PowerShell functions with my own custom attributes?

For example:

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

}
like image 744
tellingmachine Avatar asked Jul 09 '09 01:07

tellingmachine


1 Answers

Yes, of course you can!

Any type derived from Attribute which allows UsageType.All (or UsageType.Class) can be used on the function itself (i.e. above Param)

Any type derived from Attribute which allows UsageType.Property or UsageType.Field usage can be used on parameters themselves or variables.

It's not uncommon to just be lazy and use UsageType.All (e.g. the built in OutputType attribute does that).

You can even write them in PowerShell classes now

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'")
        }        
    }
}

See more examples on Kevin Marquette's blog.

There's an older example here showing how to do it in PowerShell 4 and earlier using Add-Type, although it's a little out of date now, because the particular example it shows has been integrated into PowerShell 6 and is no longer needed 😉

There are also videos

like image 118
Jaykul Avatar answered Oct 13 '22 19:10

Jaykul