chriskyfung/My-PowerShell-Scripts

🦺 Add the `#Requires` statement in the existing scripts

chriskyfung opened this issue · 0 comments

To specify the minimum version of PowerShell or any modules or snap-ins that a script file or module depends on, you can use the #Requires statement at the beginning of the file or module. The #Requires statement prevents a script from running unless the specified prerequisites are met[1][2][4].

The #Requires statement has the following syntax:

#Requires -Version <N>[.<n>]
#Requires -PSSnapin <PSSnapin-Name> [-Version <N>[.<n>]]
#Requires -Modules { <Module-Name> | <Hashtable> }
#Requires -PSEdition <PSEdition-Name>
#Requires -ShellId <ShellId> -PSSnapin <PSSnapin-Name> [-Version <N>[.<n>]]
#Requires -RunAsAdministrator

Here are some examples of how to use the #Requires statement:

#Requires -Version 5.1
#Requires -PSSnapin DiskSnapin -Version 1.2
#Requires -Modules @{ ModuleName="Hyper-V"; ModuleVersion="1.1" }
#Requires -PSEdition Desktop

To determine the minimum PowerShell version needed for a command, you can look up the command on Microsoft Docs and click the version on the left to see what the minimum number is[3]. Alternatively, you can use the Get-Module (Get-Command <command name>).Module).PowerShellVersion command to find out what the minimum version is for a specific command[3].

It's also possible to use code to ensure that the client is using at least the minimum required PowerShell version. However, it's recommended to use the built-in #Requires statement instead[6].

Citations:
[1] https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_requires?view=powershell-7.3
[2] https://powershellisfun.com/2023/04/24/using-the-requires-statement-in-powershell/?amp=1
[3] https://www.reddit.com/r/PowerShell/comments/9fry3o/how_to_determine_minimum_ps_version_needed_for_a/
[4] https://ss64.com/ps/syntax-requires.html
[5] https://stackoverflow.com/questions/36166262/powershell-version-check-prior-to-script-execution
[6] https://blog.danskingdom.com/ensure-client-is-using-at-least-the-minimum-required-powershell-version/