ConvertTo-HashTable.ps1 Part 2

ConvertTo-HashTable.ps1 Part 2

  • Comments 1

I wrote the previous blog in the middle of watching the video.  The VERY next thing he did was to create 2 hashtables so my simple version of ConvertTo-HashTable.ps1 wouldn't work for that case.  So I made a more sophisticated version:

# ConvertTo-hashTable.ps1
#    Updated to create multiple hashtables
param(
[string] 
$key,
$value
)
Begin
{
    $hashTables  = @()
    foreach ($v in @($value))
    {
      $hashTables += @{}
    }
    $Script = $false
    if ($value -is [ScriptBlock])
    {
        $Script = $true
    }
}
Process
{
    $thisKey = $_.$Key
    for ($i = 0 ; $i -le $hashTables.Count; $i++)
    {
        $hash = $hashTables[$i]
        if (@($Value)[$i] -is [ScriptBlock])
        {
            $hash.$thisKey = & @($Value)[$i]
        }
        else
        {
            $hash.$thisKey = $_.$(@($Value)[$i])
        }
    }
}
End
{
    foreach ($hash in $hashtables)
    {
        Write-Output $hash
    }
}

I've attached the script as well.

What this does is to emit multiple hashtables - one for each VALUE you want.  So the way you would use this is:

$ht1,$ht2 = gwmi Win32_logicalDisk –Filter “DriveType = 3” | ConvertTo-HashTable DeviceId {$_.size - $_.freeSpace}, FreeSpace

I'm going to go back and finish watching the video. I may end up with a couple more versions before I'm through. ha ha. 

Jeffrey Snover [MSFT]
Windows Management Partner Architect
Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

Attachment: ConvertTo-HashTable.ps1
Leave a Comment
  • Please add 8 and 3 and type the answer here:
  • Post
  • just imho ones:

    - the initcap on begin/process/end seems weird

    - you can drop the $script var now

    - in process, i'd put @($Value)[$i] into a var to make the rest easier to read

    - since it can be more than one, rename $value to $values

    semi-related, but if you left $value out of the param, would you be able to iterate over $args as the rest of the params without having to @() ?  I haven't tried it.

Page 1 of 1 (1 items)