Skip to content

Instantly share code, notes, and snippets.

@midnightfreddie
Last active February 28, 2016 13:20
Show Gist options
  • Save midnightfreddie/3aea041a8c9dee6fb448 to your computer and use it in GitHub Desktop.
Save midnightfreddie/3aea041a8c9dee6fb448 to your computer and use it in GitHub Desktop.
# In reply to comment https://www.reddit.com/r/PowerShell/comments/47wc3x/ive_been_asked_to_come_up_with_35_questions_to/d0g8bgd
$Hash = @{
"a" = 5
"b" = 4
"c" = 3
"d" = 2
"e" = 1
}
$Hash
# Name Value
# ---- -----
# c 3
# e 1
# d 2
# b 4
# a 5
"Sort by Name (Key)"
$Hash.GetEnumerator() | Sort-Object Name
# Name Value
# ---- -----
# a 5
# b 4
# c 3
# d 2
# e 1
"Sort by Value"
$Hash.GetEnumerator() | Sort-Object Value
# Name Value
# ---- -----
# e 1
# d 2
# c 3
# b 4
# a 5
# Other hash notes
"A hash is an object with a bunch of members"
$Hash | Select-Object -First 1
# Name Value
# ---- -----
# c 3
# e 1
# d 2
# b 4
# a 5
".GetEnumerator() emits a series of objects in name/value pair"
$Hash.GetEnumerator() | Select-Object -First 1
# Name Value
# ---- -----
# c 3
# Adding notes on ordered hashes in reply to https://www.reddit.com/r/PowerShell/comments/47wc3x/ive_been_asked_to_come_up_with_35_questions_to/d0ga4p2
"Ordered hashes don't solve a sorting problem in most cases"
$OrderedHash = [ordered]@{
"a" = 5
"b" = 4
"c" = 3
"d" = 2
"z" = 0
}
$OrderedHash
# Name Value
# a 5
# b 4
# c 3
# d 2
# z 0
"Ordered hases keep the order you added the members, not sorted by the names or values"
$OrderedHash["e"] = 1
$OrderedHash
# Name Value
# a 5
# b 4
# c 3
# d 2
# z 0
# e 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment