PowerShell 中变量的好处是可以将一些命令或结果存储到变量中,从而更方便对象的操作和维护。PowerShell 中可以不指定类型声明变量,系统会自动识别并定义。PowerShell 中变量的声明是以美元符号("$")开头的,且变量名不区分大小写。
当前版本:
声明和赋值:
查看变量:
交换变量值:
重设变量:
声明只读变量:(参考 New-Variable)
Option | Description |
"None" | NOoption (default) |
"ReadOnly" | Variablecontents may only be modified by means of the -force parameter |
"Constant" | Variablecontents can't be modified at all. This option must already bespecified when the variable is created. Once specified thisoption cannot be changed. |
"Private" | Thevariable is visible only in a particular context (localvariable). |
"AllScope" | Thevariable is automatically copied in a new variable scope. |
查看当前已声明的变量:
查看变量更多属性:
删除变量值(不删除变量):
删除变量:(一般不需删除,关闭当前会话自动清除)
系统变量、自动变量:
查看环境变量:
添加、更改、删除 当前环境变量(当前会话有效):
查看、添加用户或系统环境变量:
变量作用域(全局、当前、私有、脚本):
$global
全局变量,在所有的作用域中有效,如果你在脚本或者函数中设置了全局变量,即使脚本和函数都运行结束,这个变量也任然有效。
$script
脚本变量,只会在脚本内部有效,包括脚本中的函数,一旦脚本运行结束,这个变量就会被回收。
$private
私有变量,只会在当前作用域有效,不能贯穿到其他作用域。
$local
默认变量,可以省略修饰符,在当前作用域有效,其它作用域只对它有只读权限。
全局变量和函数内部的变量:
查看变量类型:
变量类型转换:
变量类型参考:
Variabletype | Description | Example |
[array] | Anarray | |
[bool] | Yes-novalue | [boolean]$flag= $true |
[byte] | Unsigned8-bit integer, 0...255 | [byte]$value= 12 |
[char] | Individualunicode character | [char]$a= "t" |
[datetime] | Dateand time indications | [datetime]$date= "12.Nov 2004 12:30" |
[decimal] | Decimalnumber | [decimal]$a= 12 |
[double] | Double-precisionfloating point decimal | $amount= 12.45 |
[guid] | Globallyunambiguous 32-byte identification number | [guid]$id= [System.Guid]::NewGuid() |
[hashtable] | Hashtable | |
[int16] | 16-bitinteger with characters | [int16]$value= 1000 |
[int32],[int] | 32-bitintegers with characters | [int32]$value= 5000 |
[int64],[long] | 64-bitintegers with characters | [int64]$value= 4GB |
[nullable] | Widensanother data type to include the ability to contain null values. Itcan be used, among others, to implement optional parameters | [Nullable``1[[System.DateTime]]]$test= Get-Date |
[psobject] | PowerShellobject | |
[regex] | Regularexpression | $text= "Hello World" |
[sbyte] | 8-bitintegers with characters | [sbyte]$value= -12 |
[scriptblock] | PowerShellscriptblock | |
[single],[float] | Single-precisionfloating point number | [single]$amount= 44.67 |
[string] | String | [string]$text= "Hello" |
[switch] | PowerShellswitch parameter | |
[timespan] | Timeinterval | [timespan]$t= New-TimeSpan $(Get-Date) "1.Sep 07" |
[type] | Type | |
[uint16] | Unsigned16-bit integer | [uint16]$value= 1000 |
[uint32] | Unsigned32-bit integer | [uint32]$value= 5000 |
[uint64] | Unsigned64-bit integer | [uint64]$value= 4GB |
[xml] | XMLdocument |
参考:powershell 在线教程 Chapter 3. Variables