[b]变量[/b]
在程序设计中,变量是最基本的概念,它是我们表示数据的在存储时的代号。在PowerShell中,变量通常供我们在脚本中使用,它可以是数字、字符、字符串,甚至是对象。当然,和任何shell一样,它也有自己的特定的变量,如:$_ 、$Args、$Error、$Home、$PSHome等。
在PowerShell中,所有的变量以“$”开头,用“=”来给变量赋值。例如:
$StrUser = “MR″ <enter>
或者使用"set-variable”命令:
set-variable -name StrUser -value “MaRui” <enter>
需要注意的是,使用“set-variable”命令时在变量名前不需要使用“$”。
当然,在声明变量时,要回避一些特殊名称,这些名称被称作“系统保留字”,列举如下:
break | continue | do | else | elseif | filter | foreach | function | if | in | return | switch | until | where | while
屏幕输出变量值:
write-output $StrUser <enter>
或者直接输入变量名,如:
$StrUser <enter>
运行结果:
[img]http://files.jb51.net/file_images/article/201212/2012120517000139.png[/img]
[b]字符、字符串[/b]
和程序设计一样,在处理字符、字符串时,需要搞清楚数据类型。下面是PowerShell的常用数据类型说明:
PowerShell使用的数据类型
| int |
有符号,32bit |
| long |
有符号,64bit |
| double |
双精度64bit浮点 |
| single |
单精度32bit浮点 |
| string |
unicode编码字符串 |
| char |
unicode编码字符,16bit |
| byte |
无符号字符,8bit |
| decimal |
十进制数,128bit |
| array |
数组 |
| xml |
xml对象 |
| hashtable |
哈希表 |
| bool |
true、false |
我们通过几个例子来明白数据类型的意义。首先看看string的例子:
$strA = “Hello “ <enter>
$strB = “World!” <enter>
$strC = $strA + $strB <enter>
$strC <enter>
[img]http://files.jb51.net/file_images/article/201212/2012120517000140.png[/img]
对字符串的操作还有其他方法,如:
[b]替换[/b]
$strA = “hi! world!” <enter>
$strB = $strA -replace “hi!”, “Hello” <enter>
$strB <enter>
[img]http://files.jb51.net/file_images/article/201212/2012120517000141.png[/img]
[b]引用[/b]
看看下面的例子:
$strA = “MaRui” <enter>
"This is $strA.” <enter>
'This is $strA.' <enter>
[img]http://files.jb51.net/file_images/article/201212/2012120517000142.png[/img]
在PowerShell中,对数字进行运算操作十分简单,不需要过多说明,只用几个例子:
5 + 100 <enter>
$x=200+1 <enter>
$x <enter>
[int]$y=(7 + 13 * 2) / 10 <enter>
$y <enter>
[img]http://files.jb51.net/file_images/article/201212/2012120517000143.png[/img]
有时,PowerShell并不能很好的为我们自动指定数据类型,因此,在编写脚本时,请尽可能的为变量声明数据类型,以防出错。在数学运算上,有如下操作:
| + |
加 |
| - |
减 |
| * |
乘 |
| / |
除 |
| % |
取余 |
| = |
赋值 |
| ++ |
给变量加1,相当于+1 |
| -- |
给变量减1,相当于-1 |
当然,括号也是免不了要用的。