MisterSeajay
MisterSeajay

Reputation: 4659

Do curly braces mean anything in PowerShell variable declaration?

I have come across variables (or parameters) being declared like this:

${var_name} = "Hello world!"

As far as I can tell, this is no different to the following:

$var_name = "Hello world!"

I am wondering if the {} braces in the first example do or mean anything. Do they change the behaviour of the variable?

Upvotes: 28

Views: 20990

Answers (3)

Micha Wiedenmann
Micha Wiedenmann

Reputation: 20843

What might not be obvious on a first glance is that you can use any provider within ${}, for example:

${c:\tmp\foo.txt}="Hello World"       # C: uses file system provider

The effect depends on the provider. For the file system provider the example changes the content of the specified file.

Upvotes: 11

Drumor
Drumor

Reputation: 421

the {} braces use for declare variables with spaces in the middle or inside of the variable, like this:

${var_name   hello   } = "Hello world!2"

$var_name = "Hello world!"

it's not the same, 'cause you can't save data in a variable with spaces, powershell understand the variable until a space, except it's inside the braces.

Have a good day. (:

Upvotes: 11

Mike Shepard
Mike Shepard

Reputation: 18156

Curly braces in PowerShell variable names allow for arbitrary characters in the name of the variable. If there are no "pathological" characters in the variable name, then the braces are not needed and have no effect.

You'll find that "generated" code will sometimes use curly braces because they guarantee that the variable name is valid.

Upvotes: 25

Related Questions