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.
1 |
#Requires -RunAsAdministrator |
This is when the requirement is not met:
1 2 3 4 5 6 7 8 9 10 |
PS C:\Users\Paolo> echo "#requires -runasadministrator">test.ps1 PS C:\Users\Paolo> .\test.ps1 .\test.ps1 : The script 'test.ps1' cannot be run because it contains a "#requires" statement for running as Administrator. The current Windows PowerShell session is not running as Administrator. Start Windows PowerShell by using the Run as Administrator option, and then try running the script again. At line:1 char:1 + .\test.ps1 + ~~~~~~~~~~ + CategoryInfo : PermissionDenied: (test.ps1:String) [], ScriptRequiresException + FullyQualifiedErrorId : ScriptRequiresElevation |
For more information I strongly suggest you to read the help:
1 |
get-help about_requires |
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