For example:
function TestThis()
{
[MySpecialCustomAttribute]
[CmdletBinding()]
Param(...)
Process{...}
}
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With