PowerShell Tips – Attributes

Attributes are labels that we add to our code, so that we can direct the way in which the interpreter works. They are most often used when developing cmdlet interfaces, as there is a lot of work with controlling input data.

In many programming languages, when the code runs into an unexpected error, it stops. However, in scripting languages, like PowerShell, code execution continues as usual. If we want to explicitly stop code execution, we need to declare:

$ErrorActionPreference ="Stop"

Other options are “SilentlyContinue”, “Continue” and “Inquire”. We will take a look at other preferential and environmental variables in another post at some point in the future.

Declarative code tells the interpreter what to do, but the imperative code tells it how to do it. Let’s take a look at the following two examples:

[ValidateRange(0, 10)]
[int]$n = Read-Host

And:

[int]$n = Read-Host
if ($n -lt 0 -or $n -gt 10) 
{
	throw [IndexOutOfRangeException]::new()
}

The declarative code in the first example tells the interpreter to make sure that the variable in $n is between 0 and 10. Contrary to the first example, the second example uses more code, logical operations and error handling to achieve the same result.

Validation attributes are declarative because they define the case in which the variable is valid.

To use them, we need a pair of square brackets, a name, parameters (which can be empty, but they must be present) and a value that the attribute will influence. For example:

[AttributeName("param1", "param2")] $value

We can use attributes with any assignment statement we want.

A simple example of binding when declaring a variable:

[AttributeName("param1", "param2")]

$name = "value"

Example:

[ValidateSet("abc", "def", "ghi")]

$region = Read-Host

The example above returns an error, if we do not enter one of the listed values when running the code.

When we get used to using attributes on simple examples, the transition to using validation attributes on function and class parameters will be much simpler.

We can do similar things with function parameters:

function Deploy-Cluster {
   Param(
      [Parameter(Mandatory)]
      [ValidatePattern("^[a-z]+-[a-z]+-[a-z]+-[0-9]+$")]
      [string] $ClusterId
    )
}

Leave a Reply

Your email address will not be published. Required fields are marked *