變量
在程序設(shè)計(jì)中,變量是最基本的概念,它是我們表示數(shù)據(jù)的在存儲(chǔ)時(shí)的代號(hào)。在PowerShell中,變量通常供我們?cè)?a href='http://www.49028c.com/tech/jiaoben/' target='_blank'>腳本中使用,它可以是數(shù)字、字符、字符串,甚至是對(duì)象。當(dāng)然,和任何shell一樣,它也有自己的特定的變量,如:$_ 、$Args、$Error、$Home、$PSHome等。
在PowerShell中,所有的變量以“$”開頭,用“=”來給變量賦值。例如:
$StrUser = “MR″ <enter>
或者使用"set-variable”命令:
set-variable -name StrUser -value “MaRui” <enter>
需要注意的是,使用“set-variable”命令時(shí)在變量名前不需要使用“$”。
當(dāng)然,在聲明變量時(shí),要回避一些特殊名稱,這些名稱被稱作“系統(tǒng)保留字”,列舉如下:
break | continue | do | else | elseif | filter | foreach | function | if | in | return | switch | until | where | while
屏幕輸出變量值:
write-output $StrUser <enter>
或者直接輸入變量名,如:
$StrUser <enter>
運(yùn)行結(jié)果:

字符、字符串
和程序設(shè)計(jì)一樣,在處理字符、字符串時(shí),需要搞清楚數(shù)據(jù)類型。下面是PowerShell的常用數(shù)據(jù)類型說明:
| int | 有符號(hào),32bit |
| long | 有符號(hào),64bit |
| double | 雙精度64bit浮點(diǎn) |
| single | 單精度32bit浮點(diǎn) |
| string | unicode編碼字符串 |
| char | unicode編碼字符,16bit |
| byte | 無符號(hào)字符,8bit |
| decimal | 十進(jìn)制數(shù),128bit |
| array | 數(shù)組 |
| xml | xml對(duì)象 |
| hashtable | 哈希表 |
| bool | true、false |
我們通過幾個(gè)例子來明白數(shù)據(jù)類型的意義。首先看看string的例子:
$strA = “Hello “ <enter>
$strB = “World!” <enter>
$strC = $strA + $strB <enter>
$strC <enter>

對(duì)字符串的操作還有其他方法,如:
替換
$strA = “hi! world!” <enter>
$strB = $strA -replace “hi!”, “Hello” <enter>
$strB <enter>

引用
看看下面的例子:
$strA = “MaRui” <enter>
"This is $strA.” <enter>
'This is $strA.' <enter>

在PowerShell中,對(duì)數(shù)字進(jìn)行運(yùn)算操作十分簡(jiǎn)單,不需要過多說明,只用幾個(gè)例子:
5 + 100 <enter>
$x=200+1 <enter>
$x <enter>
[int]$y=(7 + 13 * 2) / 10 <enter>
$y <enter>

有時(shí),PowerShell并不能很好的為我們自動(dòng)指定數(shù)據(jù)類型,因此,在編寫腳本時(shí),請(qǐng)盡可能的為變量聲明數(shù)據(jù)類型,以防出錯(cuò)。在數(shù)學(xué)運(yùn)算上,有如下操作:
| + | 加 |
| - | 減 |
| * | 乘 |
| / | 除 |
| % | 取余 |
| = | 賦值 |
| ++ | 給變量加1,相當(dāng)于+1 |
| -- | 給變量減1,相當(dāng)于-1 |
當(dāng)然,括號(hào)也是免不了要用的。
新聞熱點(diǎn)
疑難解答
圖片精選