What is the difference between $a = $(Read-Host) and $a = (Read-Host)?

前端 未结 2 1662
小蘑菇
小蘑菇 2021-01-15 14:01

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 Parame

相关标签:
2条回答
  • 2021-01-15 14:11

    $() is for evaluating subexpressions in strings. It does nothing here.

    You don't need () around read-host either, you can simply use $a = Read-Host -Prompt 'your input here'

    (-Prompt needs a string as parameter).

    0 讨论(0)
  • 2021-01-15 14:12

    Quoting from Keith Hill's blog:

    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.

    Silly example:

    $a = (Read-Host -Prompt 'something'; echo 'foo')
    $b = $(Read-Host -Prompt 'something'; echo '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.

    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.

    0 讨论(0)
提交回复
热议问题