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.
To create a new variable, use an assignment statement to assign a value to the variable. You don't have to declare the variable before using it. The default value of all variables is $null . To get a list of all the variables in your PowerShell session, type Get-Variable .
$_ is a variable created by the system usually inside block expressions that are referenced by cmdlets that are used with pipe such as Where-Object and ForEach-Object . But it can be used also in other types of expressions, for example with Select-Object combined with expression properties.
The $_ is a variable or also referred to as an operator in PowerShell that is used to retrieve only specific values from the field. It is piped with various cmdlets and used in the “Where” , “Where-Object“, and “ForEach-Object” clauses of the PowerShell.
Variable in PowerShell starts with $ symbol. Variables in PowerShell are not case sensitive and they may contain any letters, numbers and special characters. In the case of special characters they need to enclose with {}, for example, ${Ranjan rating out of 10 is}=10.
$()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With