Arrays
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
$array[1]
Even we can use multiple indices separated by comma, in order to get multiple values.
$array[1,2,3]
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.
$hashTable["Code"]
We can also specify multiple keys to extract multiple values.
$hashTable["Id", "Code"]
Also you can use the key with dot notation
$hashTable.Code
To get all keys/values present in the HashTable
$hashTable.Keys
$hashTable.Values
Add new key in Hash Table
$hashTable["Category"] = "Office Supplies"
or
$hashTable.Add("Category", "Office Supplies")
Remove a key from Hash Table
$hashTable.Remove("Category")
Look for a key in Hash Table
$hashTable.ContainsKey("Category")
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
$array[1]
Even we can use multiple indices separated by comma, in order to get multiple values.
$array[1,2,3]
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.
$hashTable["Code"]
We can also specify multiple keys to extract multiple values.
$hashTable["Id", "Code"]
Also you can use the key with dot notation
$hashTable.Code
To get all keys/values present in the HashTable
$hashTable.Keys
$hashTable.Values
Add new key in Hash Table
$hashTable["Category"] = "Office Supplies"
or
$hashTable.Add("Category", "Office Supplies")
Remove a key from Hash Table
$hashTable.Remove("Category")
Look for a key in Hash Table
$hashTable.ContainsKey("Category")
No comments:
Post a Comment