# ============================================================================================== # # Microsoft PowerShell Source File -- Created with SAPIEN Technologies PrimalScript 2009 # # NAME: Demo-HashTable.ps1 # # AUTHOR: Jeffery Hicks , SAPIEN Technologies # DATE : 2/19/2009 # # COMMENT: Demonstration of Associative arrays in PowerShell. # # ============================================================================================== #create a hash table with values $hash=@{Name="Jeff Hicks";Title="Scripting Guru"; Url="blog.sapien.com";Extension="x123"} #view the contents $hash #create an empty hash table $hash=@{} $computername=$env:computername [ADSI]$Server="WinNT://$computername" $users=$server.psbase.children | where { $_.psbase.schemaclassname -eq "user" } #add items to the hash table foreach ($user in $users) { $hash.Add($user.name[0],($user.passwordage[0]/86400 -as [int])) } Write-Host ("There are {0} users in the hash table." -f $hash.count) #see if a key exists and if so get its value if ($hash.containsKey("administrator")) { Write-Host ("{0} Administrator Password age = {1} days" -f $computername,$hash.Item("administrator")) } #or access items by key $hash.Administrator #or like this $hash["administrator"] #view the contents of the hash table $hash #view the contents sorted by key $hash.GetEnumerator() | sort #or by value $hash.GetEnumerator() | sort value -descending #remove an item if ($hash.containskey("guest")) { $hash.remove("guest") } $hash.keys | foreach { $lastChanged=((Get-Date).AddDays(-($hash.item($_)))).ToShortDateString() $obj=New-Object PSObject $obj | Add-Member Noteproperty "Computer" $computername $obj | Add-Member Noteproperty "User" $_ $obj | Add-Member Noteproperty "PasswordAge" $hash.item($_) $obj | Add-Member Noteproperty "LastChanged" $lastChanged write $obj } | sort PasswordAge -descending | Format-Table -Autosize #remove all $hash.Clear()