powershell 变量语法 $($a)? [英] powershell variable syntax $($a)?

查看:29
本文介绍了powershell 变量语法 $($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

虽然它工作得很好,但我不知道添加 $( ) 实际上做了什么.当我执行 ($a):\calendar 时,它会返回带括号的 (variable):\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.

推荐答案

$() 是一个 子表达式运算符.意思是先评估这个,然后单独做一个独立的陈述".

$() 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)";
}

比较:

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

您还可以执行诸如 $($x + $y).ToString()$(Get-Date).AddDays(10) 之类的操作.

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

在这里,如果没有子表达式,您将得到 $a:\calendar.好吧,问题在于变量后面的冒号是运算符.具体来说,范围运算符.为了防止 PowerShell 认为您正在尝试在 a 命名空间中查找变量,作者将该变量放在子表达式中.

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.

就我过去几年使用 PS 的情况而言,没有美元符号的括号本质上也是子表达式.当在字符串中时,它们不会被评估为子表达式,但否则它们通常会.没有明显区别是一种令人沮丧的怪癖.

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.

这篇关于powershell 变量语法 $($a)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆