什么是PowerShell“特殊”变量和字符

时间:2014-04-29 16:38:17

标签: variables powershell shorthand

这个问题是为了帮助我清除PowerShell中对变量的一些困惑。我熟悉创建变量并为其赋值的概念..例如,在SharePoint中,您可以这样做:$spsite = http://site

然而,PowerShell中有很多变量可以通过各种方式使用。

例如,如果我在变量$spsite中设置网站集(就像我上面所做的那样),我可以对其进行foreach循环并遍历每个网站..

foreach ($web in $spsite)

在另一个例子中,我看到类似这样的东西

$a = 5
$b = 6
$c = 7
$d = $a,$b,$c

Foreach ($i in $d)
{ $i + 5}

在这两种情况下,我都没有为$ i或$ web分配值..但它们有某种意义或价值。我得到$ web是网站集中的每个网站。但PowerShell如何知道这一点?它只是吗?

有人可以解释一下这个和/或发给我链接到解释的地方吗?

PowerShell中还有所有这些特殊变量和特殊字符(快捷方式)的列表。例如,我相信%是foreach-object cmdlet

1 个答案:

答案 0 :(得分:3)

$i$web不是特殊变量。它们只是人们重复使用的流行名称。 foreach - 循环中当前对象的名称由您定义。

例如:

#Creating a simple array for the demonstration
$MyArrayOfAwesomeObjects = 1,2,3

foreach ($ThisVariableIsAwesome in $MyArrayOfAwesomeObjects) {

    #Here, $ThisVariableIsAwesome is the current object, and we can call methods on it.
    $ThisVariableIsAwesome.GetType()

}

IsPublic IsSerial Name  BaseType
-------- -------- ----  --------
True     True     Int32 System.ValueType
True     True     Int32 System.ValueType
True     True     Int32 System.ValueType

至于% - > Foreach-Object,这只是一个别名。您可以使用Get-Alias

查看所有别名
相关问题