Powershell在字符串中使用变量


Powershell中你可能知道使用双引号字符串展开其中变量,例如这样:

$domain = $env:USERDOMAIN
$username = $env:USERNAME

"$domain\$username"

在Powershell中只要其中变量书写规范清楚它将正常工作,再看看这个:

$domain = $env:USERDOMAIN
$username = $env:USERNAME

"$username: located in domain $domain"

失败了,因为变量后面多了个冒号,(注意编辑器中的错误标记)

这里你可以使用Powershell中“重音符”将这个特殊字符串转义,例如:

$domain = $env:USERDOMAIN
$username = $env:USERNAME

"$username`: located in domain $domain"

如果问题不是特殊字符引起的,这种方法就不需要。

 

"Current Background Color: $host.UI.RawUI.BackgroundColor"

这条双引号只解决了得到变量值,但是没有获得到这个变量及其相关属性。

为了解决类似问题,你必须使用下列技术:

"Current Background Color: $($host.UI.RawUI.BackgroundColor)"
'Current Background Color: ' + $host.UI.RawUI.BackgroundColor
'Current Background Color: {0}' -f $host.UI.RawUI.BackgroundColor

原文地址:Expanding Variables in Strings

本文链接: https://www.pstips.net/expanding-variables-in-strings.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注