Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a simple question regarding why something works the way it does and I cant seem to readily find out why. I was trying to run the following command:

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

while it works just fine, I don't know what adding the $( ) actually does. When I do ($a):calendar it would return (variable):calendar with the parenthesis, but adding the extra "$" fixes it. why?

Thank you all for your help with this terribly worded question.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
840 views
Welcome To Ask or Share your Answers For Others

1 Answer

$() is a subexpression operator. It means "evaluate this first, and do it separately as an independent statement".

Most often, its used when you're using an inline string. Say:

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

Compare that 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 the subexpression, you'd get $a:calendar. Well, the problem there is that the colon after a variable is an operator. Specifically, the scope operator. To keep PowerShell from thinking you're trying to look for a variable in the a namespace, the author put the variable in a subexpression.

As far as I've been able to tell using PS for the past few years, parentheses without the dollar sign are also essentially subexpressions. They won't be evaluated as a subexpression when within a string, but otherwise they usually will. It's kind of a frustrating quirk that there's no clear difference.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...