What is the meaning of ${} in powershell?

2020-03-15 01:20发布

I have a script where function parameters are expressed like this:

param(
   ${param1},
   ${param2},
   ${param3}
)

What does it mean? I have been unable to find documentation on this.

What's the point of writing parameters that way instead of the more usual

param(
    $param1,
    $param2,
    $param3
)

?

标签: powershell
4条回答
Root(大扎)
2楼-- · 2020-03-15 01:40

@MikeZ's answer is quite correct in explaining the example in the question, but as far as addressing the question title, there is actually more to say! The ${} notation actually has two uses; the second one is a hidden gem of PowerShell:

bracket notation examples

That is, you can use this bracket notation to do file I/O operations if you provide a drive-qualified path, as defined in the MSDN page Provider Paths.

(The above image comes from the Complete Guide to PowerShell Punctuation, a one-page wallchart freely available for download, attached to my recent article at Simple-Talk.com.)

查看更多
在下西门庆
3楼-- · 2020-03-15 01:50

They are equivalent. It's just an alternative way of declaring a variable.

If you have characters that are illegal in a normal variable, you'd use the braces (think of it as "escaping" the variablename).

查看更多
别忘想泡老子
4楼-- · 2020-03-15 01:53

They are both just parameter declarations. The two snippets are equivalent. Either syntax can be used here, however the braced form allows characters that would not otherwise be legal in variable names. From the PowerShell 3.0 language specification:

There are two ways of writing a variable name: A braced variable name, which begins with $, followed by a curly bracket-delimited set of one or more almost-arbitrary characters; and an ordinary variable name, which also begins with $, followed by a set of one or more characters from a more restrictive set than a braced variable name allows. Every ordinary variable name can be expressed using a corresponding braced variable name.

From about_Variables

To create or display a variable name that includes spaces or special characters, enclose the variable name in braces. This directs Windows PowerShell to interpret the characters in the variable name literally.

For example, the following command creates and then displays a variable named "save-items".

C:\PS> ${save-items} = "a", "b", "c" 
C:\PS> ${save-items} 
a 
b 
c
查看更多
▲ chillily
5楼-- · 2020-03-15 02:05

There is one additional usage.

One may have variable names like var1, var2, var11, var12, var101, etc. Regardless if this is desirable variable naming, it just may be.

Using brackets one can precisely determine what is to be used: assignment of $var11 may be ambiguous, using ${var1}1 or ${var11} leaves no room for mistakes.

查看更多
登录 后发表回答