Вопрос

This question is to help clear up some confusion I have with variables in PowerShell. I'm familiar with the concept of creating a variable and assigning it a value.. for example, in SharePoint, you would do this: $spsite = http://site

Yet, there are a lot of variables that come from PowerShell that can be used in various ways.

For example, if I set a site collection in a variable $spsite (like I did above), I can do a foreach loop on it and iterate through each web site..

foreach ($web in $spsite)

In another example, I see something like this

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

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

In both cases, I have not assigned a value to $i or $web.. yet they have some kind of meaning or value. I get that $web is each website in a site collection. But how does PowerShell know this? It just does?

Can someone explain this and/or send me a link to where this is explained?

Also is there a list of all these special variables and special characters (shortcuts) in PowerShell.. for example, I believe % is the foreach-object cmdlet

Это было полезно?

Решение

$i and $web aren't special variables. They are just popular names that people reuse. The name of the current object in a foreach-loop is defined by you.

Ex:

#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

As for % -> Foreach-Object, that is just an alias. You can view all aliases with Get-Alias

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top