Powershell $ syntax ($ a)?

I have a simple question as to why something works the way it is, and I cannot easily understand why. I tried to run the following command:

foreach($a in $list){set-mailboxcalendarpermissions -identity $($a):\calendar

as long as it works fine, I don't know what $( ) adds. When I do ($a):\calendar , it will return (variable):\calendar with a parenthesis, but adding an extra "$" fixes it. What for?

Thank you for your help in this terribly worded question.

+5
source share
2 answers

$() is a subexpression operator. This means "first evaluate it and do it separately as an independent operator."

Most often used when you use the inline string. Say:

 $x = Get-ChildItem C:\; $x | ForEach-Object { Write-Output "The file is $($_.FullName)"; } 

Compare this to:

 $x = Get-ChildItem C:\; $x | ForEach-Object { Write-Output "The file is $_.FullName"; } 

You can also do things like $($x + $y).ToString() or $(Get-Date).AddDays(10) .

Here, without a subexpression, you get $a:\calendar . Well, the problem is that the colon after the variable is an operator. In particular, the domain operator . So that PowerShell does not think that you are trying to find a variable in the namespace a , the author puts the variable in a subexpression.

As far as I could tell using PS over the past few years, dollar-free parentheses are also essentially sub-expressions. They will not be evaluated as a subexpression if inside the string, but otherwise they will usually be. This is a kind of frustrating quirk that there is no clear difference.

+9
source

$() is a subexpression operator that calls the calculation of the contained expressions and returns all expressions as an array (if there are more than one) or as a scalar (one value). Regular parentheses () are just a mathematical priority operator and therefore simply work in arithmetic expressions to ensure priority

It is noteworthy that $() interpreted inside the string, while () will be taken literally - it does not really matter. So the following:

 $a = "Hello" "$($a.Length)" 

gives

 5 

then

 "($a.Length)" 

gives

 "(Hello.Length)" 

As I said, $() can consist of several expressions, all of which are returned as output. () does not do this. So this is an error, because the content is not an arithmetic expression:

 (1;2) 

whereas

 $(1;2) 

evaluates the array and outputs:

 1 2 

The expression $ ($ a) is evaluated before applying the trailing scope : operator and prevents the area from being directly bound to a , instead, $a is evaluated first, and then the area is applied.

+6
source

Source: https://habr.com/ru/post/1207082/


All Articles