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

Categories

0 votes
884 views
in Technique[技术] by (71.8m points)

powershell variable syntax $($a)?

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

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

1 Answer

0 votes
by (71.8m points)

$() 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...