Thursday, February 25, 2016

Powershell v2 Finding a Hashtable Member Directly by Referencing Name

As I was working on a script to find stray folders I posted on Technet to get some help with referencing switch values:
Can I reference the switch name from within its block?
The script relies on a set of date ranges defined in a hashtable.
# Store volumenames (key) and dateranges (values -as [Array])
$volumedateranges = @{
  Vol1 = @([DateTime] 2001-01-01, [DateTime] 2001-12-31);
  Vol2 = @([DateTime] 2002-01-01, [DateTime] 2002-12-31);
}
When the script runs I dynamically reference a hashtable member by searching through the hashtable to get its key (or name depending on what you call it).  Once I have this value I pass to a Where clause (highlighted in the red below).

# Get logical disks
Get-WmiObject -Class Win32_LogicalDisk | % {
 switch($_.VolumeName)
 {
  Vol1
  {
   # Set dates
   $startdate = ($volumedateranges.GetEnumerator() | Where {$_.key -match $_.VolumeName}).Value[0]
   $enddate = ($volumedateranges.GetEnumerator() | Where {$_.key -match $_.VolumeName}).Value[1]

   # Get directories from switched drive
   Get-ChildItem -Path "$($_.DeviceID)*Data*" | `
   Where {($_.PSIsContainer) -and (Get-FolderDate $_.fullname -lt $startdate) -and (Get-FolderDate -gt $enddate)} | `
   Select $_.fullname
  }
  Vol2
  {
   # Set dates
   $startdate = ($volumedateranges.GetEnumerator() | Where {$_.key -match $_.VolumeName}).Value[0]
   $enddate = ($volumedateranges.GetEnumerator() | Where {$_.key -match $_.VolumeName}).Value[1]

   # Get directories from switched drive
   Get-ChildItem -Path "$($_.DeviceID)*Data*" | `
   Where {($_.PSIsContainer) -and (Get-FolderDate $_.fullname -lt $startdate) -and (Get-FolderDate -gt $enddate)} | `
   Select $_.fullname
  }
 }
}
mjolinor pointed out I can bypass the enumeration and use the key (name) directly within my hashtable reference with this syntax:
$startdate = $volumedateranges[$_.VolumeName][0]
$enddate = $volumedateranges[$_.VolumeName][1]
Why enumerate when I can just call directly. Much less work, more direct, and, cleaner for sure.  Thanks again hammer man.

Related Post:

0 comments:

Post a Comment

 
Copyright 2009 Information Blog
Powered By Blogger