PowerShell and Hash Table Examples (2024)

By: Tim Smith | Updated: 2017-11-23 | Comments | Related: More > PowerShell


Problem

In this tip, we'll work through some examples with PowerShell - from basic CRUDoperations to organizing and aggregating data with hash tables. We'll also generatea few errors intentionally to understand the basic structure and limitations. We'llalso look at the dynamic nature of the data in both the keys and the values andhow this can be helpful for building configurations or processing in steps whenthose steps may change.

Solution

A hash table provides a dictionary with a key-value pair, where we input a distinctkey with an associated value and can return the result as a two column table, thefirst column being the name and the second column being the value. In our firstexercise using PowerShell ISE, we'll perform basic CRUD operations with a hash table:adding values, changing a value, removing a value, getting a value, and finallyadding properties from system variables to a hash table.

The code and output are shown below.

Write-Host "Example One - Add (Insert):"$newhastable1 = @{}$newhastable1.Add("KeyOne","ValueOne")$newhastable1.Add("KeyTwo","ValueTwo")$newhastable1Write-Host "Example Two - Change (Update):"$newhastable2 = @{}$newhastable2.Add("KeyOne","ValueOne")$newhastable2.Add("KeyTwo","ValueTwo")$newhastable2.Set_Item("KeyTwo","The quick brown fox jumped over the lazy dogs")$newhastable2Write-Host "Example Three - Remove (Delete):"$newhastable3 = @{}$newhastable3.Add("KeyOne","ValueOne")$newhastable3.Add("KeyTwo","ValueTwo")$newhastable3.Remove("KeyOne")$newhastable3Write-Host "Example Four - Get (Select):"$newhastable4 = @{}$newhastable4.Add("KeyOne","Data points in one.")$newhastable4.Add("KeyTwo","Data points in two.")$newhastable4["KeyOne"]Write-Host "Example Five - Add Properties"$versionhash = @{}$versionhash.Add("OS Version:",[System.Environment]::OSVersion.VersionString)$versionhash.Add("PowerShell Version:",$PSVersionTable.PSVersion.Major)$versionhash

PowerShell and Hash Table Examples (1)

Hastable names must be unique; for an example, if we try to add KeyOnetwice to our hash table, it will fail with the message Exception calling "Add"with "2" argument(s): "Item has already been added. Key in dictionary: 'KeyOne'Key being added: 'KeyOne'.

$newhastablefail = @{}$newhastablefail.Add("KeyOne","ValueOne")$newhastablefail.Add("KeyOne","ValueFail")$newhastablefail

PowerShell and Hash Table Examples (2)

As long as the key is different, we won't get an error. For an example, we canhave different names with the same value:

$newhastablesamevalue = @{}$newhastablesamevalue.Add("KeyOne","ValueOne")$newhastablesamevalue.Add("KeyTwo","ValueOne")$newhastablesamevalue

PowerShell and Hash Table Examples (3)

If we tried the same with integers, it would also fail - we input 1 twice asa key:

$newhastablefail = @{}$newhastablefail.Add(1,"ValueOne")$newhastablefail.Add(1,"ValueFail")$newhastablefail

Neither the keys nor the values must be of the same type either, since a hashtable is a dictionary, as we see when we divide with the number values or applyregex to the strings:

$newhastablemixed = @{}$newhastablemixed.Add(1,25)$newhastablemixed.Add("a","Collies")$newhastablemixed.Add((Get-Date).Date,"Today is ")### Equals 5$newhastablemixed[1]/5### Matches$newhastablemixed["a"] -match "oll"

PowerShell and Hash Table Examples (4)

This provides us with flexibility, since we may need different types of valueswhen completing steps, adding or editing configurations, or migrating data. Foran example in practice, we add four values to a hash table and output them to aconfiguration file - the below uses the key for the configs XML tags and the valuesfor the values within the tags:

$newhashtableconfig = @{}$newhashtableconfig.Add("Symbols",30)$newhashtableconfig.Add("RefreshIntervalSeconds","1")$newhashtableconfig.Add("TickerDate",(Get-Date).AddDays(-4))$newhashtableconfig.Add("Message","All stories may be delayed five minutes.")foreach ($key in $newhashtableconfig.Keys){ $info = "<$key>" + $newhashtableconfig[$key] + "</$key>" Add-Content "E:\Sites\Ticker\ticker.confg" $info}

PowerShell and Hash Table Examples (5)

In our next example, we'll use an array of lower case alphabet characters, anditerate over a sentence string, saving each letter found in the sentence stringto the hash table, while keeping count of each character. For an example, in oursentence, "Put it in miscelaneous", it willsave the letter i as the name and the count of 3 as the value, since there are 3 in the sentence.

$letters = @("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","t","u","v","w","x","y","z")$sentence = "Put it in miscelaneous."$letterTable = @{}foreach ($eachletter in $sentence.ToCharArray()){ [string]$eachletterstring = $eachletter foreach ($letter in $letters) { if ($letter -eq $eachletterstring.ToLower()) { if ($letterTable.ContainsKey($letter)) { [int]$currentcount = $letterTable[$letter] $letterTable.Set_Item($letter,($currentcount + 1)) } else { $letterTable.Add($letter,1) } } }}$letterTable

PowerShell and Hash Table Examples (6)

By using the method ContainsKey, we can prevent adding a duplicate key- which would throw an error. If a key exists, the method returns true and if not,the method returns false:

$newhastablecontains = @{}$newhastablecontains.Add(1,2)$newhastablecontains.Add(2,4)$newhastablecontains.Add(3,8)$newhastablecontains.Add(4,16)$newhastablecontains.ContainsKey(1)$newhastablecontains.ContainsKey(3)$newhastablecontains.ContainsKey(10)

PowerShell and Hash Table Examples (7)

We can also use hash tables in steps - such as the below example where we checkwhether a path exists, get all the files by an extension, and validate if a fileexists by a date. In practice, these values could change by configuration file ortable and depending on how many steps are involved, allow for easier debugging,as in that scenario we could call the hash table, see the steps under the name,and the variables for those steps under value. The alternative would be to searchthrough the script, which may be fast or slow depending on the length.

$steptable = @{}$steptable.Add(1,"C:\ETLFiles\")$steptable.Add(2,"*.txt")$steptable.Add(3,((Get-Date).Year.ToString() + (Get-Date).Month.ToString()))if (Test-Path $steptable[1]){ $files = Get-ChildItem -Path $steptable[1] -Filter $steptable[2] foreach ($file in $files) { if ($file.BaseName -match $steptable[3]) { $file.FullName } }}

PowerShell and Hash Table Examples (8)

Next Steps
  • After going through the exercises, create and manipulate other hash tablesby using the CRUD operations.
  • From configurations with dynamic values to manipulating data with key-valuepairs, hash tables can offer a useful tool for faster development and data manipulation.

Related Articles

Using PowerShell with SQL Server Management Objects (SMO)

Retrieve a List of SQL Server Databases and their Properties using PowerShell

Setting the PowerShell Execution Policy

Monitor a SQL Server Cluster using PowerShell

How to find a specific text string in a SQL Server Stored Procedure, Function, View or Trigger

New PowerShell cmdlets to read and write SQL Server tables

PowerShell Invoke-SQLCmd outputs DataTables you can INSERT into SQL Server

Bulk Copy Data from Oracle to SQL Server

Parsing Strings From Delimiters In PowerShell

How to Query Arrays, Hash Tables and Strings with PowerShell

Getting Started with PowerShell File Properties and Methods

Create File with Content Using PowerShell

Execute SQL Server Stored Procedures from PowerShell

Call SQL Server Stored Procedures with PowerShell using Parameter Objects

Create SQL Server Database with PowerShell

PowerShell for the SQL Server DBA – Environment Setup

PowerShell for the DBA - If Else and Switch statements

PowerShell for the DBA - Basic Functions

PowerShell for the DBA - Performing DBA tasks using SQL Server CMDLETs

Run PowerShell Scripts with SQL Server Agent or Windows Task Scheduler

Popular Articles

Date and Time Conversions Using SQL Server

Format SQL Server Dates with FORMAT Function

SQL Server CROSS APPLY and OUTER APPLY

SQL NOT IN Operator

SQL Server DROP TABLE IF EXISTS Examples

SQL Server Cursor Example

Rolling up multiple rows into a single row and column for SQL Server data

How to tell what SQL Server versions you are running

Resolving could not open a connection to SQL Server errors

SQL Convert Date to YYYYMMDD

SQL Server Loop through Table Rows without Cursor

Format numbers in SQL Server

SQL Server Database Stuck in Restoring State

Concatenate SQL Server Columns into a String with CONCAT()

Add and Subtract Dates using DATEADD in SQL Server

Using MERGE in SQL Server to insert, update and delete at the same time

List SQL Server Login and User Permissions with fn_my_permissions

SQL Server Row Count for all Tables in a Database

SQL Server PIVOT and UNPIVOT Examples

Display Line Numbers in a SQL Server Management Studio Query Window

About the author

Tim Smith works as a DBA and developer and also teaches Automating ETL on Udemy.

View all my tips

Article Last Updated: 2017-11-23

PowerShell and Hash Table Examples (2024)

FAQs

How do I use a hash table in PowerShell? ›

To create a hash table in PowerShell, you'll use an @ symbol followed by an opening curly brace and a closing curly brace as shown below. Here you can see my hash table is now three lines with a key/value pair in the middle.

How to clear all values from Hashtable in PowerShell? ›

Hash table in the PowerShell session is created temporarily. It is like a variable, when the session is closed, hash table is deleted automatically. If you want to delete all the values from the hash table at once but retaining the hash table variable, you need to use the Clear() method.

How to get value from Hashtable in PowerShell? ›

PowerShell – Get Value by Key in HashTable
  1. Getting Single Value by Single Key. Use Indexer Notation. Use .Item() Method. ...
  2. Getting Multiple Values by Multiple Keys. Use -match Operator. Use ForEach-Object Cmdlet. ...
  3. Getting All Values with/without Keys. Use ForEach Loop. ...
  4. Getting Nested Value of Nested Key. Use Indexer Notation.

How to display Hashtable in PowerShell? ›

You can display the hashtable in $p and use the key-name properties to display the values. The keys in a hashtable can also be any . NET type. The following statement adds a key-value pair to the hashtable in the $p variable.

How to hash text in PowerShell? ›

PowerShell does not provide a cmdlet to compute the hash of a string. However, you can write a string to a stream and use the InputStream parameter of Get-FileHash to get the hash value.

How to convert string to hash table in PowerShell? ›

The ConvertFrom-StringData cmdlet converts a string that contains one or more key and value pairs into a hash table. Because each key-value pair must be on a separate line, here-strings are often used as the input format. By default, the key must be separated from the value by an equals sign ( = ) character.

How to retrieve value stored in hash table? ›

An element is converted into an integer by using a hash function. This element can be used as an index to store the original element, which falls into the hash table. The element is stored in the hash table where it can be quickly retrieved using hashed key.

How to check if key exists in hash table PowerShell? ›

To check if HashTable contains a key in PowerShell, use the if statement with the -contains operator. Write-Host "Key '$key' exists in the hash table." Write-Host "Key '$key' does not exist in the hash table." Key 'Name' exists in the hash table.

How to get all keys from hashtable? ›

We can use keySet() method get all keys from hashtable in java. It returns a Set object with all keys.

How to check if value exists in hashtable? ›

How to Check if Value Exists in Hashtable? To check if the value exists in a hashtable, we can make use of the “containsValue” method provided by the Hashtable class. This method returns a Boolean value indicating whether or not the specified value is present in the hashtable.

How to check hash on PowerShell? ›

You can check the hash value for a file by using the PowerShell command get-filehash and the path to the file.

How to pass hashtable as parameter in PowerShell? ›

To splat a parameter set, first create a hashtable containing key/value pairs of each parameter and parameter argument. Then, once you have the hashtable built, pass that set of parameters to the command using @<hashtable name> .

How to check if hash table is empty in PowerShell? ›

Hashtable values can be of any type, such as numbers, strings, arrays, objects, and other data types as values in a hashtable. Now, rerun the code below to check if your hashtable is empty. $name. Count -eq 0) { Write-Output "The hashtable is empty." else { Write-Output "The hashtable is not empty."

How do you check if a key is in a hashtable? ›

The ContainsKey() method of the hashtable class takes a key object as a parameter and returns true if this key object is present in the hashtable. It returns false if the element with the specified key is not present in the hashtable.

How to check if hashtable is empty? ›

To do this we can use the “Count” property of the Hashtable class that returns the number of elements in the hashtable. So if the Count property returns a 0, it will mean the hashtable is empty and if it returns a value greater than 0, the hashtable has elements.

How do I find the hash value of a file? ›

Solution:
  1. Open the Windows command line. Press Windows + R, type cmd and press Enter. ...
  2. Go to the folder that contains the file whose MD5 checksum you want to check and verify. Command: Type cd followed by the path to the folder. ...
  3. Type the command below certutil -hashfile <file> MD5. ...
  4. Press Enter.
Mar 30, 2023

How to get data from text file in PowerShell? ›

The Get-Content cmdlet can be used to retrieve the contents from a file in PowerShell. It will retrieve the contents one line at a time, storing them in an array. This allows you to use or process each line in your PowerShell script.

Can I convert hash to text? ›

You cannot. it is impossible. That's actually the point of hashes like this. They are a one way hash.

What is @{} in PowerShell? ›

@{} in PowerShell defines a hashtable, a data structure for mapping unique keys to values (in other languages this data structure is called "dictionary" or "associative array"). @{} on its own defines an empty hashtable, that can then be filled with values, e.g. like this: $h = @{} $h['a'] = 'foo' $h['b'] = 'bar'

How to convert to hashtable from a JSON in PowerShell? ›

We can use the pipeline command ConvertFrom−JSON to convert the JSON file to the custom table format and with the −AsHashtable parameter to convert the custom object to the hashtable.

How do I find the hash code of a string? ›

The hashCode() method returns the hash code of a string. where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation.

What is an example of a hash value? ›

Hash functions (hashing algorithms) used in computer cryptography are known as "cryptographic hash functions". Examples of such functions are SHA-256 and SHA3-256, which transform arbitrary input to 256-bit output.

What is hash table with example? ›

Hash Table is a data structure which stores data in an associative manner. In a hash table, data is stored in an array format, where each data value has its own unique index value. Access of data becomes very fast if we know the index of the desired data.

Can you retrieve original data from its hash value? ›

This is impossible for any good cryptographic hash algorithm. It's theoretically possible (though by design so improbable it will never happen) to guess some data that will hash to that value, but there's no way to know if it's the original data.

How do you check if a character is in a string PowerShell? ›

If you want to know in PowerShell if a string contains a particular string or word then you will need to use the -like operator or the . contains() function. The contains operator can only be used on objects or arrays just like its syntactic counterpart -in and -notin .

How to check registry key value in PowerShell? ›

One of the easiest ways to find registry keys and values is using the Get-ChildItem cmdlet. This uses PowerShell to get a registry value and more by enumerating items in PowerShell drives. In this case, that PowerShell drive is the HKLM drive found by running Get-PSDrive .

How do you check if a key exists in a HashMap? ›

Use the containsKey() method and check if a given key exists in the HashMap or not.

How to get value from hash key? ›

A hash is denoted by a set of curly braces ( {} ) which contains key-value pairs separated by commas. Each value is assigned to a key using a hash rocket ( => ). Calling the hash followed by a key name within brackets grabs the value associated with that key.

What is the difference between hashtable and array in PowerShell? ›

The difference is keys and values. Arrays hold single items in each index, while a hash table holds a key-value pair in each.

What is the difference between array and hash table in PowerShell? ›

Like many other scripting and programming languages, Windows PowerShell allows you to work with arrays and hash tables. An array is a collection of values that can be stored in a single object. A hash table is also known as an associative array and is a dictionary that stores a set of key-value pairs.

How do I know if HashMap has same value? ›

equals() to check if two HashMaps have the same entries. The way that Map. equals() works is by comparing keys and values using the Object. equals() method.

How to check if something is in a Hashtable Java? ›

contains() method is present in the HashTable class inside the java. util package. It is used to check whether or not a particular value is being mapped by any keys present in the HashTable .

How to check whether Hashtable contains specific key in Java? ›

The containsKey() method of Hashtable is used to check if a value is mapped to the specified key .

How do I check data type in PowerShell? ›

There are different data types exist for the variable like Byte, Int32, Float, String, etc. To get the variable type, we need to use the GetType() method.

What is a PowerShell hash? ›

Posted on May 24, 2022. A hash table is an array of key/value pairs, along with accompanying functions for. readily accessing or modifying values by way of their corresponding keys.

How do you test a hash function? ›

How to test hash functions? One of the leading indicators of the quality of hash functions is the probability of getting hash collisions. So one test is to check collisions at the massive input data. Usually, the distribution of hash values ​​is uniform and is tested using the Chi-square test.

How to remove key value from hashtable in PowerShell? ›

To remove the Key-value from the Hashtable, you need to use the Remove(Key) method. You cannot remove the hashtable entry with the values. You must use the key inside the Remove() method.

How to merge two hashtable in PowerShell? ›

Adding values of the hash table is simple as the adding string. We just need to use the addition operator (+) to merge two hash table values.

How to initialize hashtable PowerShell? ›

PowerShell hash tables are initialized using @{key = value; key = value} syntax. Hash table values are accessed using $table. key syntax. An empty PowerShell hash table is created using @{}.

How to check cluster status in PowerShell? ›

Executing the command below in a PowerShell prompt will report the status of Failover Cluster modules.
  1. Get-Module –ListAvailable.
  2. Import-Module FailoverClusters.
  3. Get-Command –Module FailoverClusters or Get-Command | FindStr Cluster.
  4. Get-Cluster | Format-List –Property *
  5. Get-Cluster –Domain TechGenix.com.
  6. Get-ClusterResource.
Sep 25, 2018

Does HashTable allow null keys? ›

A HashTable does not allow null keys and null values.

How do you check if a key exists in a list? ›

Using Keys() The keys() function and the "in" operator can be used to see if a key exists in a dictionary. The keys() method returns a list of keys in the dictionary, and the "if, in" statement checks whether the provided key is in the list. It returns True if the key exists; otherwise, it returns False.

What is key-value in hash table? ›

A hash table is a type of data structure that stores key-value pairs. The key is sent to a hash function that performs arithmetic operations on it. The result (commonly called the hash value or hash) is the index of the key-value pair in the hash table.

What does isEmpty do in hashtable? ›

java. util. Hashtable. isEmpty() Method
  • Description. The isEmpty() method is used to test if this hashtable maps no keys to values.
  • Declaration. Following is the declaration for java. ...
  • Parameters. NA.
  • Return Value. The method call returns 'true' if this hashtable maps no keys to values; false otherwise.
  • Exception. NA.
  • Example.

How do you check is empty or not? ›

The isEmpty() method checks whether a string is empty or not. This method returns true if the string is empty (length() is 0), and false if not.

How do you check if a HashMap is null? ›

We can easily check if HashMap is empty or not by using size() method. If size() method returns 0 then the HashMap is empty otherwise not.

How do you initialize a hash table in PowerShell? ›

PowerShell hash tables are initialized using @{key = value; key = value} syntax. Hash table values are accessed using $table. key syntax. An empty PowerShell hash table is created using @{}.

How to use DataTable in PowerShell? ›

Create DataTable In Powershell

This is a simple T-SQL query to grab the existing user databases on a SQL instance. For this we use the Invoke-SQLCmd command. Now that the objects is created you can type the variable name ($Datatable) and use the DOT notation to display the methods available.

How do you insert a hash table? ›

Create the item based on the { key: value } pair. Compute the index based on the hash function. Check if the index is already occupied or not, by comparing the key . If it is not occupied, you can directly insert it into index .

How to sort hash table PowerShell by value? ›

To sort a hashtable, use the GetEnumerator() method on the hashtable to gain access to its individual elements. Then use the SortObject cmdlet to sort by Name or Value.

How to convert array to Hashtable in PowerShell? ›

You don't have an array of elements, what you have is a single string within an array. All those elements are parts of the same item. Therefore, you need to split the string into lines, then into their delimiter, remove the trailing spaces and build your hashtable.

How to read data from user in PowerShell? ›

In PowerShell, users can retrieve the input by prompting them with Read-Host Cmdlet. It acts as a stdin and reads the input supplied by the user from the console. Since the input can also be stored as a secured string, passwords can be prompted using this cmdlet.

How to pass data to PowerShell script? ›

Passing arguments in PowerShell is the same as in any other shell: you just type the command name, and then each argument, separated by spaces. If you need to specify the parameter name, you prefix it with a dash like -Name and then after a space (or a colon), the value.

How do you display data in a table format in PowerShell? ›

If you use the Format-Table cmdlet with no property names specified to format the output of the Get-Process command, you get exactly the same output as you do without a Format cmdlet. By default, PowerShell displays Process objects in a tabular format.

What is hashing with example? ›

Hashing is an important data structure designed to solve the problem of efficiently finding and storing data in an array. For example, if you have a list of 20000 numbers, and you have given a number to search in that list- you will scan each number in the list until you find a match.

What is an example of a hash function? ›

Hash functions (hashing algorithms) used in computer cryptography are known as "cryptographic hash functions". Examples of such functions are SHA-256 and SHA3-256, which transform arbitrary input to 256-bit output.

What is a real life example of hash table? ›

Hash tables let us implement things like phone books or dictionaries; in them, we store the association between a value (like a dictionary definition of the word "lamp") and its key (the word "lamp" itself). We can use hash tables to store, retrieve, and delete data uniquely based on their unique key.

How do you write a hash function? ›

A basic hash function

If the keys are real numbers between 0 and 1, one way to create a hash function is to multiply each key by m and round off to the nearest integer to get an index between 0 and m-1. This hash function can be represented as h(k) = ⌊km⌋.

What is a hash table for dummies? ›

Hash tables are used to implement map and set data structures in most common programming languages. In C++ and Java they are part of the standard libraries, while Python and Go have builtin dictionaries and maps. A hash table is an unordered collection of key-value pairs, where each key is unique.

Top Articles
Latest Posts
Article information

Author: Tuan Roob DDS

Last Updated:

Views: 5762

Rating: 4.1 / 5 (62 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Tuan Roob DDS

Birthday: 1999-11-20

Address: Suite 592 642 Pfannerstill Island, South Keila, LA 74970-3076

Phone: +9617721773649

Job: Marketing Producer

Hobby: Skydiving, Flag Football, Knitting, Running, Lego building, Hunting, Juggling

Introduction: My name is Tuan Roob DDS, I am a friendly, good, energetic, faithful, fantastic, gentle, enchanting person who loves writing and wants to share my knowledge and understanding with you.