Powershell: Filter Hashtable - and get back a Hastable

powershell hashtable
powershell hashtable foreach
powershell hashtable multiple values
powershell foreach add to hash table
powershell hashtable contains key
powershell hashtable vs array
powershell update hashtable value
powershell hashtable parameter

Filtering a Hashtable using GetEnumerator always returns a object[] instead of a Hashtable:

# Init Hashtable
$items = @{ a1 = 1; a2 = 2; b1 = 3; b2 = 4}
# apply a filter
$filtered = $items.GetEnumerator() | ?{ $_.Key -match "a.*" }
# The result looks great
$filtered
  Name                           Value
  ----                           -----
  a2                             2
  a1                             1
# … but it is not a Hashtable :-(
$filtered.GetType()
  IsPublic IsSerial Name                                     BaseType
  -------- -------- ----                                     --------
  True     True     Object[]                                 System.Array

Is there a nice solution to this problem?

Thanks a lot for any Help!, kind regards, Tom

$filtered is an array of dictionary entries. There's no single cast or ctor for this as far as I know.

You can construct a hash though:

$hash = @{}
$filtered | ForEach-Object { $hash.Add($_.Key, $_.Value) }

Another workflow:

# Init Hashtable
$items = @{ a1 = 1; a2 = 2; b1 = 3; b2 = 4}

# Copy keys to an array to avoid enumerating them directly on the hashtable
$keys = @($items.Keys)
# Remove elements not matching the expected pattern
$keys | ForEach-Object {
    if ($_ -notmatch "a.*") {
        $items.Remove($_)
    }
}

# $items is filtered

Everything you wanted to know about hashtables, Use PowerShell and a Filter Hash Table to Speed Boot Trace Get-WinEvent [-​FilterHashtable] <Hashtable[]> [-ComputerName <String>]. FilterHashtable accepts a hash table as a filter to get specific information from Windows event logs. A hash table uses key-value pairs. For more information about hash tables, see about_Hash_Tables. If the key-value pairs are on the same line, they must be separated by a semicolon.

As the accepted answer was resulting in a BadEnumeration exception for me (but still worked), I modified it to not throw an exception and also made sure that the original HashTable is not modified by cloning it first:

# Init Hashtable
$items = @{ a1 = 1; a2 = 2; b1 = 3; b2 = 4}

$filtered = $items.Clone()

$items.Keys | ForEach-Object { 
    if ($_ -notmatch "a.*") { 
        $filtered.Remove($_) 
    }
}

Use PowerShell and a Filter Hash Table to Speed Boot Trace , I am trying to filter based on those values (which are stored as a hashtable) and am struggling figuring out how to do this. I want to be able to  Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. Generally we used String or numbers as keys. This tutorial introduces how to declare hashtable variables, create hashtables, and process hashtable using its methods.

Here's an even simpler function, it even has include and exclude functionality

function Select-HashTable {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory,ValueFromPipeline)][Hashtable]$Hashtable,
        [String[]]$Include = ($HashTable.Keys),
        [String[]]$Exclude
    )

    if (-not $Include) {$Include = $HashTable.Keys}

    $filteredHashTable = @{}
    $HashTable.keys.where{
        $PSItem -in $Include
    }.where{
        $PSItem -notin $Exclude
    }.foreach{
        $filteredHashTable[$PSItem] = $HashTable[$PSItem]
    }
    return $FilteredHashTable
}

Examples:

$testHashtable = @{a=1;b=2;c=3;d=4}

$testHashTable | Select-HashTable -Include a

Name                           Value
----                           -----
a                              1
$testHashTable | Select-HashTable -Exclude b
Name                           Value
----                           -----
c                              3
d                              4
a                              1
$testHashTable | Select-HashTable -Include a,b,c -Exclude b


Name                           Value
----                           -----
a                              1
c                              3

Topic: Filtering Based on Hash Table Contents, Hash Tables (also known as Associative arrays or Dictionaries) are a type of array to be unique, if you try to add the same key twice PowerShell will return an error A hash table is a single PowerShell object, to sort, filter or work with the  However, I have no idea how to work this into a Where-Object (if that’s what I even want to do) to Filter based on the contents of a value in the hash table. If I export all of the VMM properties to Excel, all it shows me is that the values for CustomProperty are part of a hash table, it doesn’t display any of the values.

On a modern PowerShell (5+ as far as I remember) you can use reduce pattern. For that you need to use this form of ForEach-Object:

$Hashtable.Keys | ForEach-Object {$FilteredHashtable = @{}} {
    if ($_ -eq 'Example') {
        $FilteredHashtable[$_] = $Hashtable[$_];
    }
} {$FilteredHashtable}

Yes, this snippet will return Hashtable.

Powershell Hash Tables - PowerShell, Server04 {[app, hub], [client, customer02], [backup, daily]} Server05 {[app, qlik] But this just shows a hash table (from the looks of it), with a key and value pairing. Could give some insight into the type and what options you have available. Prof. Powershell. Slice and Dice with Hash Tables in PowerShell. The Group-Object cmdlet can offer up lots of information if you extract that info through hash tables. Here's how. By Jeffery Hicks; 01/31/2012; One of the greatest benefits of Windows PowerShell is how it lets us slice and dice information with minimal effort.

[SOLVED] PowerShell, In this tip we will work through some examples with PowerShell using basic CRUD operations to organize and aggregate data with hash tables. A hash table provides a dictionary with a key-value pair, where we input a $files = Get-​ChildItem -Path $steptable[1] -Filter $steptable[2] foreach ($file in $files)  We'd recommend that you first head over to the Script Center, get your feet wet, and then come back to either ask or answer questions. We can't be everywhere at once (we know—shocking!), so we will appreciate any and all help you can give to each other to get scripting problems solved.

PowerShell and Hash Table Examples, For example, you can filter out unwanted text lines: # Store result of d---- 07/26/​2007 11:03 Backup In reality, each element returned by Dir (Get-Childitem) is really an object with a number of individual properties. PowerShell will now output them as list rather than table since the console is too narrow to show them all. I am going to start with a basic technical description of what hashtables are in the general sense as used by most programming languages before I shift into the other ways Powershell makes use of them. A hashtable is a data structure much like an array, except you store each value (object) using a key. It is a basic key/value store.

Chapter 4. Arrays and Hashtables, Hash Tables are convenient but are not true objects. This is bad because function ConvertTo-Object($hashtable) You can also turn this into a pipeline filter. I'm new to powershell and trying to get the length of a HashTable (to use in a for loop), but I can't seem to get the length of the HashTable to output anything.

Comments
  • Hi briantist, thank you very much for your fast & complete answer! I could not believe that there is no single cast or ctor for this, but you're probably right. At least, the workaround is transparent & usable :-)
  • You probably want to replace $items.Keys with @($items.Keys) to not enumerate collection while you remove items from it.
  • You need to use @() or $(). Plain parenthesis will not fix the problem.
  • @PetSerAl or I can be a little clearer and just use a separate variable :-p
  • You still need to use $keys = @($items.Keys) or @($keys) | ForEach-Object .... You need to make a copy of collection before you start enumerating it. Assigning to variable do not make that copy.