Created
January 8, 2020 21:17
-
-
Save Goadstir/968ce7d8d4d52cb9519f80b5b7e11169 to your computer and use it in GitHub Desktop.
PowerShell: Ensure a PowerShell Module is available for Script or Function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ##### | |
| # Require Module as part of a Script | |
| ##### | |
| # This examples checks for available PowerCLI module: VMware.VimAutomation.Core | |
| # Add "#REQUIRES" to the top of your .ps1 file | |
| # Use -Modules to specify a Module name | |
| # If the required modules are not in the current session, Windows PowerShell imports them. | |
| # If the modules cannot be imported, Windows PowerShell throws a terminating error. | |
| # https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_requires?view=powershell-6 | |
| # ----- begin | |
| #REQUIRES -Modules VMware.VimAutomation.Core | |
| # ----- end | |
| ##### | |
| # Add Module as part of a function: | |
| ##### | |
| # This examples checks for available PowerCLI module: VMware.VimAutomation.Core | |
| # If the Module isn't found it attempts to import it. If that fails it writes a warning | |
| # ----- begin | |
| if ((Get-Module VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null) { | |
| Import-Module VMware.VimAutomation.Core -ErrorAction Stop -ErrorVariable Error | |
| If ($Error) { | |
| Write-Warning -Message "Can't find VMware PowerShell Module!" | |
| } | |
| } | |
| # ----- end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment