$a = $(Read-Host) 和 $a = (Read-Host) 有什么区别? [英] What is the difference between $a = $(Read-Host) and $a = (Read-Host)?

查看:62
本文介绍了$a = $(Read-Host) 和 $a = (Read-Host) 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须查看我的前同事留下的一些脚本,我很好奇他为什么在参数中使用 $a = $(Read-Host -Prompt "Write something")部分而不是 $a = (Read-Host -Prompt "Write something").

I have to review some scripts what my Ex-Colleague left behind and I am very curious why he is using $a = $(Read-Host -Prompt "Write something") in the Parameters section rather than $a = (Read-Host -Prompt "Write something").

我已经在单个脚本中对其进行了测试,但到目前为止还没有发现任何差异.我已经通过谷歌和 StackOverFlow 进行了搜索,但到目前为止还没有找到任何可能有什么区别的线索.也许我的搜索方法不好.

I have tested it in a single script but haven't seen any difference so far. I have searched thru the google and StackOverFlow but haven't find any clue so far what could be the difference. Maybe my searching methods are bad.

推荐答案

引用自 Keith Hill 的博客:

分组表达式 ()、子表达式 $() 和数组子表达式 @() 之间有什么区别? 分组表达式可以只包含一条语句.一个子表达式可以包含多个分号分隔的语句.每个语句的输出都会影响子表达式的输出.数组子表达式的行为就像子表达式,除了它保证输出将是一个数组.这产生不同的两种情况是 1) 根本没有输出,因此结果将是一个空数组;2) 结果是一个标量值,因此结果将是一个包含标量值的单元素数组.如果输出已经是一个数组,那么使用数组子表达式对输出没有影响,即数组子表达式不会将数组包裹在另一个数组中.

What’s the difference between grouping expressions (), subexpressions $() and array subexpressions @()? A grouping expression can contain just a single statement. A subexpression can contain multiple semicolon separated statements. The output of each statement contributes to the output of the subexpression. An array subexpression behaves just like a subexpression except that it guarantees that the output will be an array. The two cases where this makes a difference are 1) there is no output at all so the result will be an empy array and 2) the result is a scalar value so the result will be a single element array containg the scalar value. If the output is already an array then the use of an array subexpession will have no affect on the output i.e. array subexpressions do not wrap arrays inside of another array.

愚蠢的例子:

$a = (Read-Host -Prompt 'something'; echo 'foo')
$b = $(Read-Host -Prompt 'something'; echo 'foo')

第一条语句(带有分组表达式)将抛出错误,因为分组表达式中不能有多个语句.第二个语句将起作用并在通过 Read-Host 输入的文本后附加一行foo".

The first statement (with the grouping expression) will throw an error, because you cannot have multiple statements in a grouping expression. The second statement will work and append a line "foo" to the text entered via Read-Host.

在您的示例场景中 ($a = (Read-Host -Prompt 'something')$a = $(Read-Host -Prompt 'something')) 它没有任何区别.更准确地说,在这种情况下您不应该使用分组表达式或子表达式运算符,因为它们在那里没有任何用途.

In your example scenario ($a = (Read-Host -Prompt 'something') vs. $a = $(Read-Host -Prompt 'something')) it doesn't make any difference. More precisely, you shouldn't use either grouping expression or subexpression operator in that scenario, because they have no purpose there.

这篇关于$a = $(Read-Host) 和 $a = (Read-Host) 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆