Skip to content

Instantly share code, notes, and snippets.

@marcgeld
Last active June 22, 2017 19:11
Show Gist options
  • Save marcgeld/debcfbeeaf49c66111686207d44bbf74 to your computer and use it in GitHub Desktop.
Save marcgeld/debcfbeeaf49c66111686207d44bbf74 to your computer and use it in GitHub Desktop.
Powershell Collections HashTables (Dictionaries)
# PowerShell Collections HashTables (Dictionaries)
[Hashtable] $firstTable = @{
mykey = "myvalue"
label = "value"
akey = ”cat”
someOtherKey = "dog"
intValueKey = 123
}
Write-Host "1. Table: " ( $firstTable | Format-Table | Out-String ) -ForegroundColor Yellow
Write-Host "2. Get 'mykey' Value: " ( $firstTable.'mykey' | Out-String ) -ForegroundColor Yellow
Write-Host "3. Get 'mykey' Value: " ( $firstTable["mykey"] | Out-String ) -ForegroundColor Yellow
Write-Host "4. Get 'mykey' Value: " ( $firstTable.item("mykey") | Out-String ) -ForegroundColor Yellow
[Hashtable] $secTable = @{
myOtherKey = "myOtherValue"
otherLabel = "otherValue"
bkey = ”bird”
aNewKey = "owl"
otherIntValueKey = 456
}
Write-Host "5. Table: " ( $secTable | Format-Table | Out-String ) -ForegroundColor Cyan
$strongTypedDictionary = New-Object "System.Collections.Generic.Dictionary``2[string,int]"
$strongTypedDictionary.strongKeyInt = 1234
$strongTypedDictionary.Add( "specialKey", 1234 )
Write-Host "6. Table: " ( $secTable | Format-Table | Out-String ) -ForegroundColor Gray
Try
{
$strongTypedDictionary.strongKey = "strongValue"
}
Catch
{
#$ErrorMessage = $_.Exception.Message
#$FailedItem = $_.Exception.ItemName
Write-Host ( $_.Exception | Format-Table | Out-String ) -ForegroundColor Red
}
Write-Host "Table: " ( $strongTypedDictionary | Format-Table | Out-String ) -ForegroundColor Green
# Add collections
$collectionOfAll = $firstTable + $secTable + $strongTypedDictionary
Write-Host "Table: " ( $collectionOfAll | Format-Table | Out-String ) -ForegroundColor Cyan
# Loop over collection and copy
$newCollection = @{}
$collectionOfAll.GetEnumerator() | ForEach-Object {
$newCollection.Add( $_.Key, $_.Value )
Write-Host "Key: " ( $_.Key | Out-String ) "Value: " ( $_.Value | Out-String ) -ForegroundColor Cyan
}
Write-Host "Table: " ( $newCollection | Format-Table | Out-String ) -ForegroundColor DarkRed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment