Skip to content

Instantly share code, notes, and snippets.

@Goadstir
Created January 8, 2020 21:17
Show Gist options
  • Select an option

  • Save Goadstir/968ce7d8d4d52cb9519f80b5b7e11169 to your computer and use it in GitHub Desktop.

Select an option

Save Goadstir/968ce7d8d4d52cb9519f80b5b7e11169 to your computer and use it in GitHub Desktop.
PowerShell: Ensure a PowerShell Module is available for Script or Function
#####
# 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