How to write great PowerShell functions!
Tags: powershell, posh, devops, sysadmin
Published: 2018-12-12 12:08:32



---
title: How to write great PowerShell functions!
published: true
description: A deeper dive into PowerShell Functions and how to write stable, maintainable and readable code.
tags: PowerShell,POSH,devops,sysadmin
cover_image: https://thepracticaldev.s3.amazonaws.com/i/gu1hsqx0mdxp4st5evip.png
canonical_url: https://theinfradev.pro/05-howtowritegreatpowershellfunctions.html
---
<p>So far I have talked about the <a href="https://theinfradev.pro/01-whatisaninfradev.html">InfraDev's mission</a>, and what languages and tools you might use, so now I think it is time to look at some concrete examples of how people commonly write PowerShell functions, and then how to improve them to be more stable, readable, and maintainable while living up to the standards of the Powershell community. One of the key skills in an InfraDev’s life, is the ability to write functions. Functions allow us to: <p>
<ul>
<li> Re-use and share code by making standard implementations.
<li> Encapsulate and therefore hide our implementation (not for security, but readability).
<li> Make clear Entry and Exit points to different behaviours.
<li> Change a swiss army knife into a hammer
</ul>
<p></p>
<h1><b>Let's start with a common way people write functions </b></h1>
<h3><i>I have heard it is good to start at the beginning</i></h3>
<p>I have chosen a rather simple and common form of a function. We are going to provide config data (Computername) and then return services data narrowed down to just the Name and Status properties.
</p><p>
<blockquote>
$GLOBAL:ComputerName = 'Server01' <p>
Function Get-ServiceData <p>
<ul>{<ul>Get-Service -ComputerName $ComputerName | Select-Object -Properties Name,Status</ul>}</ul>
Get-ServiceData
</blockquote><p>
<ul>
<p> So what are the key features of this Function?
    <li> $Computername is out of scope and so is declared as a Global variable. This is a very fragile and just all-round bad practice. Bad Coder! Bad!
    <li> The data we are returning is instead printed to the console (sometimes called Stdout). This is bad for the purposes of extending the use of the function. In fact our function is not returning any data.
    <li> If get-service fails for any reason - we get an error, but nothing returns to our console (std out). Worse, because we were using write-host, we have no way of checking what happened! This is not good if we ever want to use this as a chain of functions or check programmatically whether the function succeeded or failed.
</ul>
<p>
<blockquote> 
Things you might not know: "What is StdIn / StdOut?" (Linux information project definition)
Standard output, sometimes abbreviated stdout, refers to the standardized streams of data that are produced by command line programs (i.e., all-text mode programs) in Linux and other Unix-like operating systems. These standardized streams, which consist of plain text, make it very easy for the output from such programs to be sent to a devices (e.g., display monitors or printers) or to be further processed by other programs." <a href=http://www.linfo.org/standard_output.html>more...</a><p>
</blockquote> 
<p></p>
<h1><b>Let's make this function better</b></h1>
<h3><i>It's time to get technical?</i></h3>
<p>
<blockquote>
$ComputerName = 'Server01'<p>
Function Get-ServiceData ($ComputerName) <p>
<ul>{<ul>$Service = Get-Service -ComputerName $Computername
    <p>Return $Service</ul>}</ul>
$RemoteServices = Get-ServiceData -ComputerName $ComputerName
</blockquote><p>
<ul>
    	<li> $ComputerName is in scope as we are passing it into this function as a parameter. This not only stops the global variable issue, but also means that other people using this function don’t have to magically know that they must declare this variable first.
    	<li> The Get-Service data is now added to a variable and is properly returned as output of this function. This provides for re-use of the output.
	<li> Further, we are also capturing the Return of our function in the $RemoteServices variable which we can then either evaluate and use further or just write to the console.
     	<li> We haven’t fixed all the flaws, because If Get-Service fails for any reason - we still return nothing and anything relying on the return of this function is out of luck.
</ul><p>
Is this best implementation? No, this is still a fragile implementation, but we have resolved some issues around returning the data and passing in data<p>
<p></p>
<h1><b>Let's go all the way to stable, maintainable code</b></h1>
<h3><i> This won’t be javascript then j/k ;)</i></h3>
<p>
<blockquote>
$ComputerName = 'Server01'<p>
$RemoteServices = "No data"<p>
Function Get-ServiceData<p>
<ul>{
<ul>[CmdletBinding(SupportsShouldProcess)] Param([string]$ComputerName)
<p><p>$Service = "Unable to retrieve data"<p>
$Service = Get-Service -ComputerName $Computername <p>
Return $Service <p></ul>
}
</ul><p>
$RemoteServices = Get-ServiceData -ComputerName $ComputerName
</blockquote>
<p>
<ul>
    <li> $Computername is in scope as we are passing it as a parameter into this function. <p>
    <li> We have also given ourselves extra PowerShell cmdlts such as -whatif and -confirm through using the <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_cmdletbindingattribute?view=powershell-6">[CmdletBinding(SupportsShouldProcess)]</a> syntax. Rather than the () we used before, now we are using best practice and changing our function into a proper 1st class PowerShell cmdlet. <p><p>
    <li> We declared that the input data is a string. This provides a type check to make sure we are giving the right type of variable and if not, it will cast it as a string anyway. While the function may fail to provide us the data we want, it will provide data.
    <li> Get-Service data is added to a variable that is already initialised. If Get-Service fails to retrieve any data, our original data will be kept. If it succeeds our data will be overwritten by the object returned.
    <li> If Get-Service fails for any reason - we get an error message.
    <li> Finally $RemoteServices is also initialised as a string 'No data' which is no longer a null or undefined variable. This also means if Get-Service fails we will then have our error declared and ready to be returned. Therefore, we know that if we get this back as the return, the Get-Service cmdlet failed.
</ul>
<p></p>
<h1><b> Let’s wrap this up </b></h1>
<h3><i> Finally, some good news! </i></h3>
<p>
Each of these implementations would have worked and without rigorous testing we might have even considered them working functions. Up until they didn't, and the wrong data was fed in, or the wrong data came back. What I have tried to show here is how we can use a couple of key principles to provide stability to our functions. <p><p>
Yes, the function is longer, and yes we have also nailed down a few concrete details such as variable types which is perhaps not in the dynamic nature of PowerShell - but by doing this we have made this function safer in the overall context and we have also made sure our hypothetical tool wouldn't error out due to nulls or failures in the implementation itself. Instead when we get bad data, we can recognise and refactor to compensate. <p><p> 
In further posts I will go into how to apply the same techniques in different styles of functions and start working with classes and objects. For now I hope the takeaway is that with a few changes to writing style we can create more stable code, that still provides the same data in an easy to read format.
<p></p>
<h4><i>
To get updates on my new articles, follow me on Twitter <a href="https://twitter.com/theinfradev" target="_blank" rel="noopener">@theinfradev</a> </i></h4>