This question already has answers here:
What is the difference between $a = $(Read-Host) and $a = (Read-Host)?

(2个答案)


3年前关闭。




之间有什么区别
Write-Host (Get-Date) # just paren


Write-Host $(Get-Date) # dollar-paren

仅举一个简单的例子,paren中的内容可以是任何内容。两者之间有什么区别吗?

我认为自己对PS有一定的经验,但是这些小问题困扰着我,尤其是在代码审查等过程中。有没有人能找到足够详细的“语言在这里是如何工作的”的丰富资源来得出这类问题的答案?

最佳答案

子表达式($(...))包含一个StatementBlockAst。它可以接受任意数量的语句,意味着关键字(ifforeach等),管道,命令等。解析类似于begin/process/end这样的命名块的内部。

paren表达式((...))可以包含单个 ExpressionAst,它是AST的有限子集。语句和表达式之间最显着的区别是不解析关键字。

$(if ($true) { 'It worked!' })
# It worked!

(if ($true) { 'It worked!' })
# if : The term 'if' is not recognized as the name of a cmdlet, function,
# script file, or operable program. Check the spelling of the name, or
# if a path was included, verify that the path is correct and try again.
# At line:1 char:2
# + (if ($true) { 'It worked' })
# +  ~~
#     + CategoryInfo          : ObjectNotFound: (if:String) [], CommandNotFoundException
#     + FullyQualifiedErrorId : CommandNotFoundException

同样,正如其他人指出的那样,子表达式将用双引号引起来的字符串扩展。

关于powershell - ()和$()之间的区别,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47274532/

10-16 12:13