August 25, 2015

PowerShell - Arrays and Hash Tables

In PowerShell script, the easiest way to create an array is to use comma separator:
$array = 1,2,3,4,5

For sequential numbers you can use a short syntax:
$array = 1..15

In PowerShell arrays, even you can place values with multiple data types.
$array = "PowerShell", "Version", 3.0

Another sysntax to create array is to use @() construct
$array = @(1, "PowerShell", "Version", 3.0)

You can access array member with zero-based index

Even we can use multiple indices separated by comma, in order to get multiple values.

Add a new item in array:
$array += "new item"

Hash Tables
To create a hash table, we use @{} instead of @(). Key-value pairs will be stored in hash table separated by semi-colons:
$hashTable = @{Id=1; Code="I001"; Name="Laptop"}

Access a key in Hash Table.

We can also specify multiple keys to extract multiple values.
$hashTable["Id", "Code"]

Also you can use the key with dot notation

To get all keys/values present in the HashTable

Add new key in Hash Table
$hashTable["Category"] = "Office Supplies"
$hashTable.Add("Category", "Office Supplies")

Remove a key from Hash Table

Look for a key in Hash Table

No comments:

Post a Comment