PowerShell – Function Parameters & .NET Attributes

ArgumentTransformationAttributes are attached to function parameters. They intercept the value coming in and optionally transform it before it is assigned to the target parameter. This is how the powershell type system is enforced:

function Foo ( [string]$str ) { ... }
(gi function:foo).parameters.str.attributes
TypeId
------
System.Management.Automation.ArgumentTypeConverterAttribute
System.Management.Automation.ParameterAttribute

This type converter derives from ArgumentTransformationAttribute. It uses the public utility type [Management.Automation.LanguagePrimitives] (which is full of cool stuff btw) to coerce incoming types to the designated type constraint, in this case [string].

As an aside, you can use the credential attribute on a function parameter too:

function do-something ([system.management.automation.credential()]$cred) { $cred }
do-something # get-credential dialog pops up if $cred is not explicitly passed

And while a little strange but definitely empowering from a future extensibility point of view, you can decorate parameters with entirely inappropriate attributes:

function Foo ( [obsolete($true)][string]$bar ) { ... }

System.ObsoleteAttribute is used in C#/VB.NET to tell the compiler that usage of the decorated item should raise a warning (false) or error (true)

blog comments powered by Disqus

About the author

Irish, PowerShell MVP, .NET/ASP.NET/SharePoint Developer, Budding Architect. Developer. Montrealer. Opinionated. Montreal, Quebec.

Month List

Page List