PowerShell Hashtable

PowerShell - Hashtable

#### Hashtable
#array

$numbers = 1..9
$numbers
$numbers[4]

#Hashtable
#1st Approach
$HT = @{}

#2nd Approach
$HT = @{
Tony = 30
Rony = 40
Sam = 35
}

$HT

# 3rd Approach -Inline
$HT = @{Tony = 30;Rony = 40; Sam = 35}
$HT

## Ordered Hashtable
$HT = [Ordered]@{Tony = 30;Rony = 40; Sam = 35}
$HT

#### Adding key and value to a HT
# Method 1
$HT.Add("Sony", 33)
$HT

# Method 2
$HT["Rohan"] = 25
$HT

# Method 3
$HT."Ramesh" = 20
$HT

# Method 4
$HT = $HT + @{"Rohit" = 21}
$HT

# Accessing the Paris out of HashTable

# Approach 1 - Index Key
$HT["Sony"]

# Approach 2 - Multiple
$HT["Sony", "Rohan"]

# Approach 3 - All the Values of All the Keys
$HT.Keys
$HT.Values
$HT.Sony

$HT.33
$HT|Measure-Object
$HT.GetEnumerator()|gm
$HT|gm
$HT.GetEnumerator()|where{$_.value -eq 33}

#### Iteration against each item of a Hashtable

foreach($entry in $HT)
{"The age of $HT.key is $HT.Value"} # Got error

# Approach 1
$HTKeys = $HT.Keys
foreach($prashant in $HTKeys)
{"The age of $prashant is $($HT.$prashant)"}

# Approach 2 - Enumeration

foreach($prashant in $HT.GetEnumerator())
{"The age of $($prashant.name) is $($prashant.Value)"}

# Making Conditions and Logics Using Hashtable
$HT.Keys -like "Sony"

$HT = @{
Tony = 30
Rony = 40
Sam = 35
}

$HT.ContainsKey("Tony")
$HT.ContainsValue(33)

# Removing Key Values from Hashtable
$HT.Remove("Rony")
$HT
$HT.Clear()
$HT

### Custom Colom Name
$HT
$HT|ft name,@{Name = "age"; expression = {$_.Value}}

## Sorting HT

$HT|Sort-Object -Property Name
$HT.GetEnumerator() | Sort-Object -Property Name

# Table with Multiple Coloms

$HT = @{
"Type" = "Car"
"Color" = "Red"
"Brand" = "Maruti"
}
$HT

$HT = [PsCustomObject]@{
"Type" = "Car"
"Color" = "Red"
"Brand" = "Maruti"
}
$HT | export-csv .\abc.csv

image-20220110113024107

相信未来 - 该面对的绝不逃避,该执著的永不怨悔,该舍弃的不再留念,该珍惜的好好把握。
原文地址:https://www.cnblogs.com/keepmoving1113/p/15783748.html