Simple Tests That Can Make Your PowerShell Scripts More Reliable

 Image of a laptop screen with a coding interface on it.
Test your code!

PowerShell scripts can serve any number of purposes. It’s no surprise, then, that they’re a favorite tool for automating various management and maintenance tasks. Even so, things can sometimes go wrong. Even a well-written, thoroughly tested script can sometimes error out due to external factors.

For example, a script may produce an error because it can’t connect to a network resource. Fortunately, you can include some simple checks into your PowerShell scripts. This will save you the hassle and reduce the chances of external errors.

In this guide, I’ll walk you through 3 different tests you can implement into your PowerShell scripts. Shall we start with #1?

1. Testing the Secure Channel

Many PowerShell scripts perform Active Directory management tasks. For example, you can use a PowerShell script to set up Active Directory accounts for new users automatically. 

Of course, a script performing domain-related activities will most likely need to be running on a PC with a valid trust relationship with a domain controller. This is something you can test for in your PowerShell script.

The cmdlet that tests a domain trust relationship is Test-ComputerSecureChannel. 

This cmdlet returns a Boolean value of True if the trust relationship works properly. Conversely, it’ll return False if the trust relationship is faulty

Pro Tip

If the secure channel isn’t working properly, you can also append the Repair switch to the command. That’ll force Windows to repair the secure channel between the computer and the Active Directory. You can see an example of this in the figure below:

Screenshot of the Test-ComputerSecureChannel cmdlet.
If necessary, you can repair the secure channel.

Okay, so how would you use this in a PowerShell script? You could combine the Test-ComputerSecureChannel cmdlet with an If-Then statement. Such a statement might look like this:

$A=Test-ComputerSecureChannel

If ($A -eq $True){Run-MyFunction} Else {Run-RepairFunction}

In the block of code above, I’m assigning the value generated by the Test-ComputerSecureChannel variable to a variable called $A. 

If $A is $True, I’m calling an imaginary function named Run-MyFunction. Conversely, if it’s $False, I’m calling a different function named Run-RepairFunction. In the real world, the Run-RepairFunction would likely attempt to repair the secure channel and test it again.

If the test succeeds, it’ll then call the Run-MyFunction. This will do whatever the script means to do.

Now that you’ve secured your channel, it’s time to test your connection next.

2. Testing the Connection for a Reliable PowerShell Script

Sometimes, you want your PowerShell script to perform an action on a remote system. In that case, consider testing the connection to that remote system before performing any actions. 

In PowerShell, this check will use the Test-Connection cmdlet.

The Test-Connection cmdlet is the PowerShell equivalent of the PING command. It sends ICMP packets to the specified destination. The only parameter you need is the TargetName parameter, the remote system’s name. You can, however, specify multiple targets. 

Screenshot of the Test-Connection cmdlet.
The Test-Connection cmdlet is very similar to the PING command.

Unlike the Test-ComputerSecureChannel cmdlet, the Test-Connection cmdlet doesn’t return a Boolean value that you can test against. You can design a PowerShell script to call a function only if the connection is good. Here’s an example:

If (Test-Connection -TargetName DC.PoseyLab.com -Quiet) {Run-MyFunction}

In the command above, the -Quiet switch prevents the test results from appearing on the screen. If the test succeeds, the command calls the Run-MyFunction function.

Great, now, your PowerShell scripts can test the security of and connection to different channels. Let’s move on to the final test.

3. Testing the Path

Another useful test you can perform in a PowerShell script is a path test. PowerShell scripts will sometimes use string manipulation to create a path dynamically. You can test to see if this path is valid before you try to write any data to it. 

Test the validity of your paths with the Test-Path cmdlet.

For example, a script needs to write data to C:\Data. You, as the script’s author, might store the path in a variable, then test against this variable.

Screenshot of the Test-Path cmdlet
Check if your folder exists with this cmdlet.

In the screen capture above, a variable named $MyPath stores the path C:\Data. The Test-Path cmdlet is then finding out if the path exists. In this case, the cmdlet returned a value of False. That means the path doesn’t exist

Pro Tip

If this code existed in a script, you can use the New-Item cmdlet to create the folder on the fly.

The Bottom Line

You don’t have to include tests in your PowerShell scripts. However, when you prevent PowerShell from encountering an error more often, your script’s reliability will also improve. In this guide, I showed you 3 different tests you can implement. 

The first test allows you to check a channel’s trust relationship. The second one helps you check the connection. Finally, the last test validates the existence of your paths.

Implementing these tests into your PowerShell scripts will help you save time figuring out what external factors caused an issue. They’ll even reduce the likelihood of errors in the first place.

Do you have more questions about PowerShell script tests? Check out the FAQ and Resources below.

FAQ

If a PowerShell script test fails, how can I terminate the script?

If a test fails, it’s best to build code into the script to remediate the error. That way, the script can run as intended. Terminate the script with the Exit command if you can’t fix the problem.

Does the Test-MyConnection test deliver reliable results in every situation?

Not necessarily. Like the PING command, Test-MyConnection uses ICMP packets. In this case, if the destination host has a firewall that blocks ICMP packets, the test will fail even if the connection is good. 

How would you use the Exit command to end the script when a test fails?

You can do this in many ways, but the easiest option is to include the Exit command in an Else statement. For example: If (Boolean Value) {Run-MyFunction} Else {Exit}. As an alternative, you could also use a hash table.

Can the Test-Path cmdlet be used to test paths defined by environment variables?

Absolutely. Suppose, for example, you wanted to check to see if a user profile was valid. You could use a command such as Test-Path $Profile -IsValid. The command would return a value of $True if the profile specified in the environment variable was valid.

Does PowerShell provide a way to test the registry?

You can use the Test-Path cmdlet to test a registry path, just like a storage path. Just append the registry location to the -Path parameter. The Test-Path cmdlet will also return a value of $True if the registry path exists.

Resources

TechGenix: Adding Custom Error Messages to PowerShell

Learn how to add custom error messages to your PowerShell scripts here.

TechGenix: Suppressing PowerShell Errors

Read more on how to suppress PowerShell errors here

TechGenix: Remedy “Team Not Recognized” Error

Find out what to do if PowerShell produces a Term Not Recognized error here.

Microsoft: Test-Path cmdlet Documentation

Discover Microsoft’s documentation for the Test-Path cmdlet here.

Microsoft: Test-Connection cmdlet Documentation

Find Microsoft’s documentation for the Test-Connection cmdlet here.

Microsoft: Test-ComputerSecureChannel cmdlet Documentation

Read Microsoft’s documentation for the Test-ComputerSecureChannel cmdlet here.

Leave a Comment

Your email address will not be published.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Scroll to Top