PowerShell (2)variables

首先谢谢小玉分享的cheat-sheet连接。很有用啊。不过我还是得先系统学习一下,以后就仗着那张cheat-sheet了。 连接也放在这儿:

http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=7097

下午会很忙,明天接着学。

  1. Variables

Your own variable

singular

  • Declareyour own variable: $varName=value,the type will be refined to the type of value when the variable is automatically created by PowerShell.
  • Declare strong typed variable: [typeName]$VarName=value
  • Using special char in variable name: use {} to enclose the name
  • Populate several variables with values simultaneously,

o  Same value:  such as $a=$b=$c=1.5

o  Different value: $a, $b = 10,20

  • List variables declared:

o  All: Dir variable:

o  Filtered:Dir variable:*value*

  • Delete variable: delvariable:\name
  • Variable related cmdlets:

o  Clear-variable: clears the contents of a variable, but not thevariable itself, set to NULL. The type will be preserved.

o  Get-variable: get the variable object, not the value, sounds like getting the pointer variable.

o  New-variable: create a new variable and can set special variable options

o  Remove-variable: deletes the variable, and its contents, as longas the variable is not constant or is created by the system

o  Set-variable: reset the value of variable or variable optionssuch as a description and creates a variable if it doesn’t exist.

  • Create readonly variable: new-variable[varName] –value [value] –option ReadOnly

o  You can delete a user-defined readonly variable by specifying –force option for deleting: delvariable:\[varname] –force

o  To change the value, you must delete and redefine the variable

  • Create constants: new-variable[varName] –value [value] –option Constant

o  You cannot delete a constant variable, even with –force option.

o  You cannot overwrite the value either.

Array

Both array and hash table support clone. $varName.Clone()

  • You can create an array by assign multi-line output of cmdlet: $result=Dir
  • Declare $arr = v1,v2,v3,v4 or $arr=@( v1,v2,v3,v4)
  • Declare $arr=v1..v2, very useful to define an array with continuous integers.
  • Emptyarray: $arr = @()
  • Strongly typed arr: [typename[]]$varName
  • Access element: $ArrVar[n],   n=-length..length-1, this is very interesting
  • Update existing arr is in fact recreate another new arrary, normally

o  Append element: $arr += newValue

o  Add element: $arr = $arr[0..insert-1] + @(newValue)+ $arr[insert..length-1]

o  Remove element: $arr = $arr[0..del-1] + $arr[del+1..length-1]

Hash tables

It’s a list ofkey-value pairs.

  • Declare: $varName = @{Key1=value1;key2=values2…}
  • Access value: $varName[“Keyname”] or $varName.KeyName
  • List keys: $varName.keys
  • List values: $varName[$varName.keys]
  • You can store an array into a value, i.e. $test = @{ value1 = 12; value2 = 1,2,3 }
  • Insert new key: $varName.NewKey=ItsValue
  • Modify value: $varName.Key=newValue
  • Delete key: $varName.remove(“keyName”)

Automatic PowerShell variablesare variables created by PowerShell

  • Dir variables:
  • Dir variable:|Sort-Object Name|Format-TableName, Description -autosize –wrap
  • Current user:$HOME
  • Currentprocess: $PID
  • CurrentPowerShell profile: $PROFILE
  • Windows folder: $env:windir
  • List all env variables: dir env:
  • Create new environment variable: $env:MyVariable=myValue
  • Delete environment variable: delenv:\varName
  • $(expression)will create an ad-hoc variable, so you can embed the variable in anotherexpression to access property of the ad-hoc variable:

ENVIRONMENT variable; $env

Ad-hoc variable

$file = DirC:\Users\v-cshao\Documents\test.txt

PS D:\temp>”the size of the file is $($file.Length) bytes.”

the size of the file is 28934 bytes.

Following won’twork:

PS D:\temp>”the size of the file is $file.Length bytes.”

the size of the file is C:\Users\v-cshao\Documents\test.txt.Lengthbytes.

Variable scope and visibility:

  • Private scope: $private:test=1,the variable will be created only in the current scope and not passed to other scopes.
  • Local scope: $local:test=1,variable will be created only in the local scope, it’s default scope, local variables can beread from scopes originating from the current scope, but not modified.
  • Script scope: $script:test = 1,the variable is valid only in a script, but valid everywhere in it. A functionin a script can address other variables defined in a script, might not defined inside the function
  • Global scope: $global:test =1.This variable is valid everywhere.

Variable types

Variable type Description Example
[array] An array
[bool] Yes-no value [boolean]$flag = $true
[byte] Unsigned 8-bit integer, 0…255 [byte]$value = 12
[char] Individual unicode character [char]$a = “t”
[datetime] Date and time indications [datetime]$date = “12.Nov 2004 12:30”
[decimal] Decimal number [decimal]$a = 12
$a = 12d
[double] Double-precision floating point decimal $amount = 12.45
[guid] Globally unambiguous 32-byte identification number [guid]$id = [System.Guid]::NewGuid()
$id.toString()
[hashtable] Hash table
[int16] 16-bit integer with characters [int16]$value = 1000
[int32], [int] 32-bit integers with characters [int32]$value = 5000
[int64], [long] 64-bit integers with characters [int64]$value = 4GB
[nullable] Widens another data type to include the ability to contain null values. It can be used, among others, to implement optional parameters [Nullable“1[[System.DateTime]]]$test = Get-Date
$test = $null
[psobject] PowerShell object
[regex] Regular expression $text = “Hello World”
[regex]::split($text, “lo”)
[sbyte] 8-bit integers with characters [sbyte]$value = -12
[scriptblock] PowerShell scriptblock
[single], [float] Single-precision floating point number [single]$amount = 44.67
[string] String [string]$text = “Hello”
[switch] PowerShell switch parameter
[timespan] Time interval [timespan]$t = New-TimeSpan $(Get-Date) “1.Sep 07”
[type] Type
[uint16] Unsigned 16-bit integer [uint16]$value = 1000
[uint32] Unsigned 32-bit integer [uint32]$value = 5000
[uint64] Unsigned 64-bit integer [uint64]$value = 4GB
[xml] XML document