Using arrays and hash tables
In PowerCLI, you can create a list of objects. For example, "red","white","blue"
is a list of strings. In PowerShell, a list of terms is called an array. An array can have zero or more objects. You can create an empty array and assign it to a variable:
PowerCLI C:\> $Array = @()
You can fill the array during creation using the following command line:
PowerCLI C:\> $Array = @("red","white")
You can use the +=
operator to add an element to an array:
PowerCLI C:\> $Array += "blue" PowerCLI C:\> $Array red white blue
If you want to retrieve a specific element of an array, you can use an index starting with 0
for the first element, 1
for the second element, and so on. If you want to retrieve an element from the tail of the array, you have to use -1
for the last element, -2
for the second to last, and so on. You have to use square brackets around the index number. In the next example, the first element of the array is retrieved using the following command line:
PowerCLI C:\> $Array[0] Red
If you want to test whether an object is an array, you can use:
PowerCLI C:\> $Array -is [array] True
There is a different kind of an array called a hash table. In a hash table, you map a set of keys to a set of values. You can create an empty hash table using the following command line:
PowerCLI C:\> $HashTable = @{}
You can fill the hash table during creation using the following command line:
PowerCLI C:\> $HashTable = @{LastName='Doe';FirstName='John'}
To add a key-value pair to a hash table, you can use the following command line:
PowerCLI C:\> $HashTable["Company"]='VMware'
To show the contents of the hash table, just display the variable:
PowerCLI C:\> $HashTable Name Value ---- ----- Company VMware FirstName John LastName Doe
If you want to retrieve a specific key-value pair, you can use:
PowerCLI C:\> $HashTable["FirstName"] John
To retrieve all of the hash table's keys, you can use the Keys
property:
PowerCLI C:\> $HashTable.Keys Company FirstName LastName
To retrieve all of the values in the hash table, you can use the Values
property:
PowerCLI C:\> $HashTable.Values VMware John Doe
If you want to test whether an object is a hash table, you can use:
PowerCLI C:\> $HashTable -is [hashtable] True
In the next section, hash tables will be used to create calculated properties.