Powershell单双引号字符串的区别

最近做一些脚本自动化的事情,发现一个很有意思的东西,如下,如果用户账户包含了$符号,就会抛出一个“User cannot be found”的异常。

New-SPSite $CommunityUrl -OwnerAlias "ASIAPACIFIC`\$ExSquareDEV001" -Name "$CommunityName" -Template "STS#0" -ContentDatabase $CommunityDatabase
New-SPSite : User cannot be found.

image

上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\

由于后面的认成了变量,而并没有赋值,这个时候就为空,输出就是前面的字符串了。

image

如果使用单引号,

变量赋值:$ExSquareServiceAccount = 'ASIAPACIFIC\$ExSquareDEV001'

输出变量值:ASIAPACIFIC\$ExSquareDEV001

整个字符串不会进行变量替换,直接输出。

image

posted @ 2012-03-21 11:11  Lambert Qin  Views(801)  Comments(0Edit  收藏  举报