最近做一些指令碼自動化的事情,發現一個很有意思的東西,如下,如果使用者賬戶包含了$符號,就會拋出一個“User cannot be found”的異常。
New-SPSite $CommunityUrl -OwnerAlias "ASIAPACIFIC`\$ExSquareDEV001" -Name "$CommunityName" -Template "STS#0" -ContentDatabase $CommunityDatabase
New-SPSite : User cannot be found.
上MSDN搜尋了一下,發現了一篇文章講述到了這個原因:http://technet.microsoft.com/en-us/library/ff730965.aspx
Quotation Marks in Windows PowerShell
First, let's review the basic distinction between single and double quotation marks in the Windows PowerShell language. It concerns the interpretation of variables.
Double quotes. When a command or expression that includes variables is enclosed in double quotes ("), the variables are replaced by their values before the command is executed.
Single quotes. When a command or expression that includes variables is enclosed in single quotes ('), the variables are not replaced by their values. Instead, they are interpreted literally.
There's actually a lot more to it – nested quotes and doubled quotes and escaped quotes and quotes in here-strings -- but these are the basics. For the rest, at the Windows PowerShell prompt, type:
大意是由於$是PowerShell變數的標誌符號,所以不同的引號會做不同的處理。
雙引號內的PowerShell變數會先計算出值,然後輸出。
單引號內的PowerShell變數作為字串直接輸出。
看下面的一個樣本:
使用雙引號賦值,
變數賦值:$ExSquareServiceAccount = "ASIAPACIFIC\$ExSquareDEV001"
輸出變數值:ASIAPACIFIC\
由於後面的認成了變數,而並沒有賦值,這個時候就為空白,輸出就是前面的字串了。
如果使用單引號,
變數賦值:$ExSquareServiceAccount = 'ASIAPACIFIC\$ExSquareDEV001'
輸出變數值:ASIAPACIFIC\$ExSquareDEV001
整個字串不會進行變數替換,直接輸出。