---
title: PowerShell Tutorial: Mastering Scriptblocks, Arrays and Hashtables
description: Learn how to use PowerShell scriptblocks for reusable code, arrays for data collections, and hashtables for key-value pair management in this practical hands-on tutorial with real-world examples.
canonical: https://adamtheautomator.com/powershell-scriptblocks-tutorial/
---

# PowerShell Tutorial: Mastering Scriptblocks, Arrays and Hashtables

> Learn how to use PowerShell scriptblocks for reusable code, arrays for data collections, and hashtables for key-value pair management in this practical hands-on tutorial with real-world examples.

Source: https://adamtheautomator.com/powershell-scriptblocks-tutorial/

---

- PowerShell Tutorial: Mastering Scriptblocks, Arrays and Hashtables Tap to hide Home

- Tutorials

- Guidebooks

- Instructors

- Get Paid to Write

- Advertising

- Recommended Resources

- About Adam

                Search for:

-

-

-

-

# PowerShell Tutorial: Mastering Scriptblocks, Arrays and Hashtables

        Published:27 November 2024 - 3 min. read

- PowerShell

          [](https://adamtheautomator.com/author/adam-bertram/)

            [Adam Bertram](https://adamtheautomator.com/author/adam-bertram/)

            Read [more tutorials](https://adamtheautomator.com/author/adam-bertram/) by Adam Bertram!

-

-

        [](https://specopssoft.com/product/specops-password-auditor/?utm_source=adamtheautomator&utm_medium=referral&utm_campaign=adamtheautomator_referral_na&utm_content=display)
        Audit Active Directory for stale users, weak passwords, and other security risks with [Specops Password Auditor](https://specopssoft.com/product/specops-password-auditor/?utm_source=adamtheautomator&utm_medium=referral&utm_campaign=adamtheautomator_referral_na&utm_content=text).

Table of Contents

- Leveraging Scriptblocks for Reusable Code
- Harnessing the Power of Arrays and Generic ListsWorking with Arrays
- Managing Elements in Generic Lists
- Streamlining Data Management with Hashtables
- Conclusion

                XFacebookLinkedIn
                As you dive deeper into PowerShell, you’ll encounter three core components essential for any PowerShell user: scriptblocks, arrays, and hashtables.

Scriptblocks allow you to encapsulate and execute reusable pieces of code; arrays let you organize and manipulate data collections. At the same time, hashtables provide a powerful way to store and access key/value pairs.

Whether you're a beginner or looking to refine your skills, understanding these concepts will significantly enhance your ability to write effective PowerShell scripts.

If scriptblocks, arrays, and hashtables are part of a larger move into automation development, compare [Educative developer learning paths for interactive software engineering practice](https://educative.pxf.io/c/1454808/1657818/19245) before choosing a paid platform. The best fit is readers who want structured practice with reusable code patterns after this PowerShell walkthrough.

## Leveraging Scriptblocks for Reusable Code

When you run any command or code, that code is called an expression. It’s a finite bit of code that PowerShell executes.

For example, to check if a file exists, you can use the Test-Path command:

Test-Path -Path C:\file.txt

This command is an expression. If you need to run this command in multiple places in your script, you can wrap it in curly braces to create a scriptblock.

$myScriptBlock = { Test-Path -Path C:\file.txt }

The scriptblock looks like a regular string.

$myScriptBlock

But when you append an ampersand (&), PowerShell runs the code inside the scriptblock.

& $myScriptBlock

Scriptblocks allow you to store and execute code in a variable as needed, making them versatile and reusable. Scriptblocks are used in various areas in PowerShell and are an essential concept to understand.

## Harnessing the Power of Arrays and Generic Lists

Previously, we worked with single values like strings, numbers, or Boolean values. Let’s now explore collections of objects, starting with arrays.

Arrays serve as a basic data structure in PowerShell, facilitating the management of collections of related items. By using arrays, you can consolidate multiple values into a single variable, enhancing the organization and efficiency of data management.

Consider a color picker script that contains four colors: blue, white, yellow, and black.

$colorPicker = @('blue','white','yellow','black')

#### Working with Arrays

Arrays in PowerShell are indicated by the @ symbol, with elements separated by commas inside parentheses. You can read and manipulate these elements as a single set.

For instance, read the entire array.

$colorPicker

To read a specific element, reference its index starting from zero (0).

$colorPicker[0]
$colorPicker[2]
$colorPicker[3]

You can also use the range operator to read a sequence of elements.

$colorPicker[1..3]

Elements in an array can be added, removed, or modified, just like a scalar value.

To change the first element (0):

$colorPicker[0] = 'pink'
$colorPicker

For adding (+) a new element:

$colorPicker = $colorPicker + 'orange'
$colorPicker

Or use a shortcut to add the element (+=):

$colorPicker += 'brown'
$colorPicker

When adding multiple elements at once:

$colorPicker += @('pink','cyan')
$colorPicker

## Managing Elements in Generic Lists

Besides arrays, you can use a different type of collection called a list or, more specifically, a generic list.

$colorPicker = [System.Collections.Generic.List[string]]@('blue','white','yellow','black')
$colorPicker

This code converts the array into a System.Collections.Generic.List of strings.

With this list, you can add elements using the Add() method.

$colorPicker.Add('gray')
$colorPicker

Or remove elements using the Remove() method.

$colorPicker.Remove('gray')
$colorPicker

## Streamlining Data Management with Hashtables

Another robust data structure in PowerShell is hashtables. While arrays are excellent for handling lists of items, hashtables offer a more advanced way to store and retrieve data using key/value pairs.

This capability makes hashtables ideal for tasks where you must quickly look up values based on unique identifiers.

Now, let's explore hashtables as follows:

$users = @{
 abertram = 'Adam Bertram';
 raquelcer = 'Raquel Cerillo';
 zheng21 = 'Justin Zheng'
}
$users

Unlike arrays, hashtables store a label or key that describes the value.

For example, this hashtable maps usernames to their full names.

You can read elements using dot notation or brackets.

$users['abertram']
$users.abertram

Next, to get a list of keys or values:

$users.Keys
$users.Values

If you prefer to see items in a nicely formatted style:

Select-Object -InputObject $users -Property *

When adding elements to a hashtable, reference the key in brackets and assign a value.

$users['phrigo'] = 'Phil Rigo'
$users

To check if a hashtable contains a particular key, use the ContainsKey() method.

This method returns $true if the key exists or $false if not.

$users.ContainsKey('johnnyq')
$users.ContainsKey('phrigo')
$users

And finally, to remove an element, use the Remove() method with the key.

$users.Remove('raquelcer')
$users

## Conclusion

With an understanding of scriptblocks, arrays, and hashtables, you now have a versatile toolkit for managing data and reusable code in PowerShell. These core concepts make your scripts cleaner and more efficient and lay the foundation for tackling more advanced PowerShell tasks.

Continue to build on these skills, and you’ll find new ways to automate and streamline your workflows in PowerShell!

  Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

  [Explore ATA Guidebooks](https://adamtheautomator.com/ata-guidebooks/)

## More from ATA Learning and Partners

- ### Recommended Resources! Recommended Resources for Training, Information Security, Automation, and more!

- ### Get Paid to Write! ATA Learning is always seeking instructors of all experience levels. Regardless if you’re a junior admin or system architect, you have something to share. Why not write on a platform with an existing audience and share your knowledge with the world?

- ### ATA Learning Guidebooks ATA Learning is known for its high-quality written tutorials in the form of blog posts. Support ATA Learning with ATA Guidebook PDF eBooks available offline and with no ads!

## Categories

- IT Ops

- Cloud

- DevOps

- Home Ops

- Information Security

- Software Development

## Site

- Home

- Tutorials

- Guidebooks

- Instructors

- Get Paid to Write

- Advertising

- Recommended Resources

- About Adam

        Copyright 2026&copy; ATA Learning | [Privacy Policy](https://adamtheautomator.com/privacy/)

                                                        Don't be left behind with the ATA Learning Newsletter!

Looks like you're offline!
