Behind-the-scenes management of Windows Powershell variables _powershell

Source: Internet
Author: User
Tags argumentlist constant table name visibility

Creating a variable in PowerShell generates a Psvariable object in the background that contains not only the value of the variable, but also other information about the variable, such as a description of write-only protection.
If you output a variable in PowerShell, only the value of that variable is output. Not being able to display other information about it, if you want to see other retention information for a variable, you need the base class Psvariable object for the variable, which can be obtained by the get-variable command, and the following example shows how to view all the information for a variable.

Ps> $a =get-date
ps> get-variable a

Name              Value
----              -----
a               2011/12/8 17:52:02

ps> get-variable A | fl *

Name    : A
Description:
Value    : 2011/12/8 17:52:02
visibility:public
Module   :
ModuleName:
Options   : None
Attributes: {}

Modify option settings for a variable
PowerShell handles a variable's psvariable object, mainly to be able to update the variable's option settings. You can either use the command set-variable, or you can change it directly after you get the Psvariable object. For example, change the description of a variable:

ps> $str = "I am a variable"
ps> $var =get-variable str
ps> $var

Name              Value
----              -----
Str              I'm a variable

ps> $var | fl *

Name    : str
Description:
Value    : I am a variable
Visibility:public
Module   :
modulename:
Options   : None
Attributes: {}

ps> $ Var. description= "I know you are a variable"
ps> $var | fl *
Name    : str
Description: I know you are a variable
Value    : I'm a variable.
visibility:public
Module   :
modulename:
Options   : None
Attributes: {} If you do not want to add a temporary variable $var to store the psvariable, you can use PowerShell subexpression

ps> (get-variable str). Description= "The description of the variable has changed;"
ps> get-variable Str |
The description of the format-table name,description Name Description----                            -----------
str                             variable has changed;

Write protection for activating variables
You can manipulate the option settings for a variable, such as write protection for a variable, and you need to set option to "ReadOnly"

ps> $var = "Mossfly"
ps> set-variable var-option "ReadOnly"
ps> (get-variable var).
the Options ReadOnly
ps> set-variable var-option "None"-force ps>
(get-variable var). Options
None

Options for variables
The option for a variable is an enumeration value that contains:
' None ': Default setting
' ReadOnly ': variable read only, but can be updated with the-force option.
"Constant": once a constant is declared, it cannot be updated at the current console.
' Private ': visible only in the current scope, not across other scopes
"Allscope": Global, can run through any scope

Type specification for variables
Each variable has its own type, and this specific type is stored in the Psvariable object's Attributes[system.management.automation.psvariableattributecollection] property, If this attributes is empty, you can store any type of data for the variable, PowerShell will choose the appropriate type. Once this attributes attribute is determined, it is not possible to store the data at random. For example, to hold an integer for $var, a weak type, so the Attributes property is empty, and you can assign it a string. But if you give the $var type, hold an integer, and assign it a different type, the interpreter will automatically attempt the conversion, and if it cannot, it throws an exception. Then if you have to update the type of the $var variable, you can use (get-variable var). Attributes.clear (), empty the Attributes so that the strong type is converted to a weak type.

 ps> $var =123 ps> (get-variable var). Attributes ps> $var. GetType (). FullName System.Int32 ps> $var = "string" ps> (get-variable var). Attributes ps> $var. GetType (). FullName System.String ps> [int] $var =123 ps> (get-variable var). Attributes typeid------System.Management.Automation.ArgumentTypeConverterAttribute ps> $var. GetType (). FullName System.Int32 ps> $var = "a" ps> $var ps> $var. GetType (). FullName System.Int32 ps> $var = "Doomsday of 2012" Cannot convert value "2012 Armageddon" to Type "System.Int32".
Error: "Input string is not in a correct format." At Line:1 char:5 + $var <<<< = "2012 World Doomsday" + Categoryinfo:metadataerror: (:) [], argumenttransformationmetadataexception + fullyqualifiederrorid:runtimeexception PS> (Get-Variable var). Attributes.clear () ps> (get-variable var). Attributes ps> $var = "The end of the 2012 world" ps> $var. GetType (). FullName System.String 

Verifying and checking the contents of variables
The Attributes property of a variable Psvariable object can store some attachment conditions, such as limiting the length of a variable so that it is validated when the variable is assigned, and the following shows how to limit the length of a string variable to between 2-5.

ps> $var = "constraint variable"
ps> $condition = New-object System.Management.Automation.ValidateLengthAttribute- ArgumentList 2,5
ps> (get-variable var). Attributes.Add ($condition)
ps> $var = "Limit"
ps> $var = "The hero of the carving"
ps> $var = "See the Hero biography of the Eagle" the
variable cannot be validated because the value to see the shot carving hero biography is not a valid value for the var variable.
At line:1 char:5
+ $var <<<< = "Watch The shooting Hero biography"
  + categoryinfo     : metadataerror: (:) [], validationmetadataexception
  + fullyqualifiederrorid:validatesetfailure

There are 5 kinds of commonly used variable content verification, respectively:
Validatenotnullattribute: Limit variable cannot be empty
Validatenotnulloremptyattribute: Limit variable is not equal to NULL, cannot be an empty string, cannot be an empty collection
Validatepatternattribute: Limit variables to meet established regular expressions
Validaterangeattribute: Limiting the range of values for a variable
Validatesetattribute: Restricting the set of values for a variable

Validatenotnullattribute Example

Ps> $a =123
ps> $con =new-object System.Management.Automation.ValidateNotNullAttribute
ps> ( Get-variable a). Attributes.Add ($con)
ps> $a =8964
ps> $a = $null


This variable cannot be validated because the value is not a valid value for variable a.
Location: 1 Characters: 3

+ $a <<<< = $null
  + categoryinfo     : metadataerror: (:) [], validationmetadataexception
  + fullyqualifiederrorid:validatesetfailure

example, note that @ () is an empty array.

ps> $con =new-object System.Management.Automation.ValidateNotNullOrEmptyAttribute ps> (get-variable a). Attributes.clear () ps> (Get-variable a). Attributes.Add ($con) ps> $a = $null The variable cannot be validated because the "value is not" a valid value for the a var
Iable. At Line:1 char:3 + $a <<<< = $null + categoryinfo:metadataerror: (:) [], validationmetadataexception + fullyqualifiederrorid:validatesetfailure ps> $a = "" The variable cannot be validat
Ed because the value is not a valid value for the A variable. At Line:1 char:3 + $a <<<< = "" + Categoryinfo:metadataerror: (:) [], validationmetadataexception + fullyqualifiederrorid:validatesetfailure ps> $a =@ () variable cannot be valida
Ted because the value system.object[] is isn't a valid value for the A variable. At Line:1 Char:3 + $a <<<< =@ () + Categoryinfo:metadataerror: (:) [], validationmetadataexception + fullyqualifiederrorid:validatesetfailUrevalidatepatternattribute example, verify the email format ps> $email = "test@mossfly.com" ps> $con =new-object System.Management.Automation.ValidatePatternAttribute "b[a-z0-9._%+-]+@[a-z0-9.-]+. [A-z] {2,4}b "ps> (get-variable email). Attributes.Add ($con) ps> $email = "abc@abc.com" ps> $email = "abc@mossfly.com" ps> $email = "author@gmail.com" PS > $email = "www@mossfly" The variable cannot to validated because the value www@mossfly is isn't a valid value for the Emai
L variable. At Line:1 char:7 + $email <<<< = "Www@mossfly" + categoryinfo:metadataerror: (:) [], validationmetadataexception + fullyqualifiederrorid:validatesetfailurevalidaterangeattribute example, verifying the month 1-12 PS> $month =1 ps> (get-variable month). Attributes.Add ($ (new-object system.management.automation.validaterangeattribute-argumentlist 1,12)) PS> $month = ps> $month =12 ps> $month =18 The variable cannot be validated because the value of not a valid value for the MO
Nth variable. At Line:1 Char:7
+ $month <<<< =18 + categoryinfo:metadataerror: (:) [], validationmetadataexception + fullyqualifiederrorid:validatesetfailure Validatesetattribute example, verify gender PS> $sex = " Male "ps> $con =new-object system.management.automation.validatesetattribute-argumentlist" male "," female "," Confidential "PS> ( get-variable sex). Attributes.Add ($con) ps> $sex = "female" ps> $sex = "Not male not female" the variable cannot be validated because the value no man not a V
Alid value for the sex variable. At Line:1 char:5 + $sex <<<< = "Not male or female" + Categoryinfo:metadataerror: (:)
 [], validationmetadataexception + fullyqualifiederrorid:validatesetfailure

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.