Skip to the main content.

Unlocking the Power of PowerShell: Tips for Success

Enhance script reliability by using PowerShell classes

Protect your PowerShell scripts from misconfiguration. Here is a type-safe way of importing external information into your scripts.

Add type safety with PowerShell classes

In the final step of our mini-series, we’ll add robustness and resilience to reading data from *.psd1: The script reading the *.psd1 file applies simple yet powerful type checking. No rogue person (or inexperienced trainee) can add unauthorized keys, typos will immediately raise alerts, and you get type safety: Data meant to be an array (list) will stay an array, even if the *.psd1 file defines just one (or no) value for this key.

Let’s try and improve this. Here is the *.psd1 file again. This time, I removed the prefix "data" from the keys as this prefix is no longer needed when all information is stored in one object, and stored the file as data_new.psd1:


@{
   # paths to important folders
   InPath = 'c:\data1', '\\server2\public\data'
   OutPath = '\\server99\public\results'
   LogPath = 'f:\local\log'

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

   # miscellaneaous settings
   TimeoutSeconds = 5400
   LogLevel = 4


Here is how we previously loaded the *.psd1 file and turned its information into an object (make sure both files are stored in the same folder):



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

# convert hash table keys into variables
$hashObject = [PSCustomObject](Import-PowerShellDataFile -Path $dataPath)


That worked great, but there was no strict type declaration that safe-guarded the imported data and made sure it was actually structured in the correct way. 

Thanks to classes (added in Windows PowerShell 5), adding this is very simple: Add a class to your script that defines the order and the data type of the object properties, then cast the object to this class.

Extra tip: For numeric lists like a "LogLevel", either use data type [int], or better yet add an enumeration with friendly names that limits the allowable numeric values to a fixed list (see below):


enum LogLevel
{
   Information = 1
   Verbose = 2
   Debug = 3
   All = 4
}

# define the structure of your input data 
class configDataScript1
{
   # paths:
   [string[]]$InPath
   [string[]]$OutPath
   [string]$LogPath

   # AD groups: 
   [string[]]$Groups

   # miscellaneaous settings
   [int]$TimeoutSeconds
   [LogLevel]$LogLevel
}

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

# safely read psd1 file (caveat: unsafe reads can execute code within psd1 file)
[configDataScript1]$externalData = [PSCustomObject](Import-PowerShellDataFile -Path $dataPath)

$externalData
$externalData.GetType().FullName 


The result is awesome: with a minimum effort, you turned *.psd1 files into a powerful and type-safe way of importing external information into your scripts.

Extra Tip: Casting objects to self-made class definitions works with a multitude of data. You can apply the same technique to imported CSV files, for example. Just make sure the class definition matches exactly the names of your properties, and each property value can in fact be converted to the data type that the class requires.

 

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

6 min read

Encoding vs encryption? Understand the difference and choose wisely!

Understanding encoding vs encryption is essential for robust data security. But what is the difference between encoding...

6 min read

Enhancing SecureString security: Best practices on different platforms

How does Windows keep SecureString safe? Dive deeper into encryption methods and uncover cross-platform security gaps...

6 min read

Cross-platform encryption risks with .NET's SecureString

Think your SecureString is safe? Not on all platforms! Discover the risks of cross-platform data encryption with ...

About the author: