Powershell單雙引號字串的區別

來源:互聯網
上載者:User

最近做一些指令碼自動化的事情,發現一個很有意思的東西,如下,如果使用者賬戶包含了$符號,就會拋出一個“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:

  • get-help about_quoting_rules

大意是由於$是PowerShell變數的標誌符號,所以不同的引號會做不同的處理。

雙引號內的PowerShell變數會先計算出值,然後輸出。

單引號內的PowerShell變數作為字串直接輸出。

看下面的一個樣本:

使用雙引號賦值,

變數賦值:$ExSquareServiceAccount = "ASIAPACIFIC\$ExSquareDEV001"

輸出變數值:ASIAPACIFIC\

由於後面的認成了變數,而並沒有賦值,這個時候就為空白,輸出就是前面的字串了。

如果使用單引號,

變數賦值:$ExSquareServiceAccount = 'ASIAPACIFIC\$ExSquareDEV001'

輸出變數值:ASIAPACIFIC\$ExSquareDEV001

整個字串不會進行變數替換,直接輸出。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.