Skip to the main content.

Unlocking the Power of PowerShell: Tips for Success

Separate config from code: Clean up PowerShell scripts with hash tables

Say goodbye to hardcoding paths and settings! Learn how to simplify your PowerShell scripts by storing config data separately with hash tables in *.psd1 files.

Clean up your scripts with hash tables –
Separate config from code!

Often, scripts require configuration information that may change, i.e. paths to relevant folders, group names, and more. 
It is always advisable to separate such information from code, and one simple approach is to use *.psd1 files. In a mini-series, we’ll look at powerful yet simple techniques that allow you to keep configuration data separated from your code.
Let’s take a look at the official PowerShell data file format: *.psd1 files always contain exactly one hash table structure, i.e.:


@{
   # paths to important folders
   dataInPath = 'c:\data1', '\\server2\public\data'
   dataOutPath = '\\server99\public\results'
   dataLogPath = 'f:\local\log'

   # AD groups 
   dataGroups = 'Technicians', 'Testers', 'Auditors'

   # miscellaneaous settings
   dataTimeoutSeconds = 5400
   dataLogLevel = 4

Note: you do not need to prepend hash table keys with a prefix like “data”, however such a prefix can later help easily identify information that you imported from an external *.psd1 file.

Hash tables support all relevant PowerShell data types, can define arrays (lists), and can also be commented for better maintenance.

There are various cmdlets and .NET APIs to read in *.psd1 content, and choosing the correct technique is crucial: since *.psd1 files may contain active commands, reading *.ps1 files with unsafe commands can accidentally invoke embedded code.

That’s why you should use cmdlets focusing on safe reading, like Import-PowerShellDataFile.

If you save above hash table to a file named data.psd1 and place this file next to the script below, the script would safely read the data from the *.psd1 file and expose it as a hash table (make sure you also save the script to a file – do not run "untitled" scripts):


# data.psd1 must be located in the same folder
$dataPath = Join-Path -Path $PSScriptRoot -ChildPath data.psd1

# safely read psd1 file (caveat: unsafe reads can execute code within psd1 file)
$dataHashtable = Import-PowerShellDataFile -Path $dataPath 

# output entire hashtable
$dataHashtable | Out-GridView -Title 'Review of all imported data from psd1 file'

# utilize settings from the hash table
$logLevel = $dataHashtable['datalogLevel']
"Current Log Level = $logLevel"

$inPath = $dataHashtable['dataInPath']
foreach ($item in $inPath)
{
   "Checking $item"


Extra tip:
Import-PowerShellDataFile ensures that no rogue *.psd1 file can accidentally trigger unwelcome action. This command was added in PowerShell 5 as a function, so in Windows PowerShell you can view its source code:

  • ${function:Import-PowerShellDataFile} | Set-ClipBoard ${function:Import-PowerShellDataFile} | Set-ClipBoard


This line copies the entire source code to your clipboard from where you can paste it into your PowerShell editor of choice. That’s complex but awesome code illustrating how you can verify PowerShell code structure using the internal parser, and much more.

In PowerShell 7, the command is now implemented as a binary cmdlet, so you can no longer view its source code this way.

 

All four tips around the topic 'utilizing external config data': 

Each tip progressively builds on creating a more manageable, efficient, and secure way to handle configuration data in PowerShell scripts, moving from basic hash tables to more advanced type-safe objects.

 

Good2know

Your ultimate PowerShell Cheat Sheet

Unleash the full potential of PowerShell with our handy poster. Whether you're a beginner or a seasoned pro, this cheat sheet is designed to be your go-to resource for the most important and commonly used cmdlets.

The poster is available for download and in paper form.

PowerShell Poster 2023

Get your poster here!

 

 

Related links 

Related posts

3 min read

PowerShell Array Caveats: Common Issues and Solutions

Here is part two of our tips on PowerShell arrays.

Let’s explore some common caveats with arrays, starting with the...

4 min read

Understanding PowerShell Arrays

PowerShell arrays are a powerful and versatile way of managing collections of data, enabling you to efficiently...

5 min read

Enhance PowerShell scripts to validate and transform data

Tired of hidden errors in your PowerShell scripts? Discover how validation and transformation attributes can bring...

About the author: