PowerShell Requires Statements

When we write code we make assumptions on the environment and the correct execution and most importantly obtaining the expecting result strictly depends on it.
I will not touch on software design or testing process, but just focus on an essential foundation that everyone should think to write better code and more efficient. Preventing to revisit code looking for answer the question of why is not working as expected.

Most of the time we’ve taken for granted that the environment is immutable or doesn’t change to a degree where impacts your code, but you haven’t check if your assumptions are true in the right place, yes in your code!
Requires statement prevents scripts from running whenever a mandatory requirement defined in the script is not met and providing a meaningful error.
A perfect example could be that your script uses a cmd-let that is available just after version 5.0 or requires to run as an administrator.
How does a requires statement look like? Generally is the placed at the top of the script.

This is when the requirement is not met:

For more information I strongly suggest you to read the help:


And about the elevation example this link contains some useful examples : https://ss64.com/ps/syntax-elevate.html

Return to : PowerShell Learning and Security Features

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.