Powershell单双引号字符串的区别
最近做一些脚本自动化的事情,发现一个很有意思的东西,如下,如果用户账户包含了$符号,就会抛出一个“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
整个字符串不会进行变量替换,直接输出。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
2009-03-21 4月1日SharePoint Designer将开始免费