• Aucun résultat trouvé

Verifying and Validating Variable Contents

Dans le document Copyright Copyright (Page 90-95)

---System.Management.Automation.ArgumentTypeConverterAttribute

# Delete type specification:

(Get-Variable a).Attributes.Clear()

# Strong type specification is removed; now the variable can

# store text again:

$a = "Test"

Verifying and Validating Variable Contents

The Attributes property of a PSVariable object can include additional conditions, such as the maximum length of a variable. In the following example, a valid length from 2 to 8 characters is assigned to a variable. An error will be generated if you try to store text that is shorter than 2 characters or longer than 8 characters:

$a = "Hello"

$aa = Get-Variable a

$aa.Attributes.Add($(New-Object `

System.Management.Automation.ValidateLengthAttribute ` -argumentList 2,8))

$a = "Permitted"

$a = "Prohibited because its length is not from 2 to 8 characters"

Because of an invalid value verification (Prohibited because

its length is not from 2 to 8 characters) may not be carried out for the variable "a".

At line:1 char:3

+ $a <<<< = "Prohibited because its length is not from 2 to 8

In the above example Add() added a new .NET object to the attributes with New-Object. You'll learn more about New-Object in Chapter 6. Along with ValidateLengthAttribute, there are additional restrictions that you can place on variables.

Restriction Category

Variable may not be zero ValidateNotNullAttribute

Variable may not be zero or empty ValidateNotNullOrEmptyAttribut e

Variable must match a Regular Expression ValidatePatternAttribute

Variable must match a particular number

range ValidateRangeAttribute

Variable may have only a particular set value ValidateSetAttribute

Table 3.7: Available variable validation classes

In the following example, the variable must contain a valid e-mail address or all values not matching an e-mail address will generate an error. The e-mail address is defined by what is called a Regular Expression. You'll learn more about Regular Expressions in Chapter 13.

$email = "tobias.weltner@powershell.com"

$v = Get-Variable email

$pattern = "\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b"

$v.Attributes.Add($(New-Object `

System.Management.Automation.ValidatePatternAttribute ` -argumentList $pattern))

$email = "valid@email.de"

$email = "invalid@email"

Because of an invalid value verification (invalid@email) may not be carried out for the variable "email".

At line:1 char:7

+ $email <<<< = "invalid@email"

If you want to assign a set number range to a variable, use ValidateRangeAttribute. The variable

$age accepts only numbers from 5 to 100:

$age = 18

$v = Get-Variable age

$v.Attributes.Add($(New-Object `

System.Management.Automation.ValidateRangeAttribute ` -argumentList 5,100))

$age = 30

$age = 110

Because of an invalid value verification (110) may not be carried out for the variable "age".

At line:1 char:7 + $age <<<< = 110

If you would like to limit a variable to special key values, ValidateSetAttribute is the right option. The variable $option accepts only the contents yes, no, or perhaps:

$option = "yes"

$v = Get-Variable option

$v.Attributes.Add($(New-Object `

System.Management.Automation.ValidateSetAttribute ` -argumentList "yes", "no", "perhaps"))

$option = "no"

$option = "perhaps"

$option = "don't know"

Verification cannot be performed because of an invalid value (don't know) for the variable "option".

At line:1 char:8

+ $option <<<< = "don't know"

The validations that you applied to variables in the above example were originally designed for cmdlets, but you can also use them for variables as well.

If you'd like to find out more about the parameters that a cmdlet accepts, you should simply examine the attribute of the cmdlet parameter and look for validation entries. The following example examines all parameters of the Get-ChildItem cmdlet and takes a closer look at the range of permitted values of the -OutBuffer parameter:

# Output all parametersets:

(Get-Command Get-ChildItem).ParameterSets (...)

# Output names of parametersets:

(Get-Command Get-ChildItem).ParameterSets | ForEach-Object { $_.Name }

Items

LiteralItems

# List all parameters of all parametersets:

(Get-Command Get-ChildItem).ParameterSets |

ForEach-Object { $_.Parameters } | ForEach-Object { $_.Name }

# Select one parameter:

$parameter = (Get-Command Get-ChildItem).ParameterSets | ForEach-Object { $_.Parameters } |

Where-Object { $_.Name -eq "OutBuffer" } | Select-Object -first 1

$parameter

Name : OutBuffer ParameterType : System.Int32 IsMandatory : False

IsDynamic : False

Position : -2147483648 ValueFromPipeline : False

ValueFromPipelineByPropertyName : False ValueFromRemainingArguments : False HelpMessage :

Aliases : {ob}

Attributes : {System.Management.Automation.

AliasAttribute, __AllParameter

Sets,System.Management.Auto mat

ion.ValidateRangeAttribute}

# Determine permitted values:

$parameter.Attributes |

Where-Object { $_.TypeId -match "ValidateRangeAttribute" } MinRange MaxRange TypeId

-- --

---0 2147483647 System.Management.Automat...

Summary

Variables store any information. The variable name always begins with the dollar sign "$". The variable name can consist of numbers, characters, and special characters like the underline

character "_". Variables are not case-sensitive. If you'd like to use characters in variable names with special meaning to PowerShell (like parenthesis), the variable name must be enclosed in braces.

PowerShell doesn't require that variables be specifically created or declared before use.

Aside from the variables that you create yourself, there are predefined variables that PowerShell creates called "automatic variables." These variables function like self-defined variables, but they already include useful key system data or configuration data for PowerShell.

PowerShell always stores variables internally in a PSVariable object. For example, it contains settings that write-protect a variable or attach a description to it (Table 3.6). It's easiest for you to activate this special function by using the New-Variable or Set-Variable cmdlets (Table 3.1).

By default, variables store any values you want. PowerShell automatically ensures that the variable type matches the value. If you'd like to set variables to a particular variable type ("strong type specification"), specify the desired type (Table 3.5) in square brackets before the variable name.

Then the variable will store only the values that match the type. In addition, the variable will now enable the special commands associated with the variable type, such as date manipulation and math with the DateTime variable type.

Every variable is created in a fixed scope, which PowerShell uses to determine the valid scope of a variable. When PowerShell starts, an initial variable scope is created, and every script and every function receive their own respective scope. You may specify a special scope by typing the name of the desired scope before the variable name and separating it with a colon from the variable name.

You can use the local:, private:, script:, and global: scopes, to address local and global variables. In addition, further providers can make their own scopes available, which enable you to address their information just like normal variables. For example, environment variables, which can be accessed through env: (Table 3.2).

Finally, direct variables are special variable types. Variable names determine their values. Either a valid file path is specified as a valid file path, and the variable outputs the contents of this data object, or the variable name consists of PowerShell code in parentheses. PowerShell then recalculates the respective "contents" of the variable.

CHAPTER 4.

Dans le document Copyright Copyright (Page 90-95)