Home > other >  Powershell - Check if specific modules are installed and take action if not installed
Powershell - Check if specific modules are installed and take action if not installed

Time:07-03

new to stackoverflow and novice at Powershell, so go easy.

I'm looking for a way for a Powershell script to check if specific modules are installed. If not then give a message asking if they would like to install those not installed. If all are installed then proceed with the script.

I've seen the '#requires -Module' option but I want to provide a better prompt rather than the Powershell red text.

For reference, I want to check if AzureAD, ExchangeOnlineManagement, and MSOnline modules are installed

Any help appreciated.

Regards, Lee

CodePudding user response:

To offer an alternative to Steven's helpful answer that handles the missing modules as a group :

# Define all required modules
$modules = 'AzureAD', 'ExchangeOnlineManagement', 'MSOnline'

# Find those that are already installed.
$installed = @((Get-Module $modules -ListAvailable).Name | Select-Object -Unique)

# Infer which ones *aren't* installed.
$notInstalled = Compare-Object $modules $installed -PassThru

if ($notInstalled) { # At least one module is missing.

  # Prompt for installing the missing ones.
  $promptText = @"
  The following modules aren't currently installed:
  
      $notInstalled
  
  Would you like to install them now?
"@
  $choice = $host.UI.PromptForChoice('Missing modules', $promptText, ('&Yes', '&No'), 0)
  
  if ($choice -ne 0) { Write-Warning 'Aborted.'; exit 1 }
  
  # Install the missing modules now.
  # Install-Module -Scope CurrentUser $notInstalled
}

CodePudding user response:

As alluded to in your question, there are a few ways to ensure modules are available to a script or module. Modules can define other modules as well as other prerequisites. #Requires can be used, but neither facility will prompt or otherwise install a module. Instead, they will prevent the loading or running of the dependent script etc.

If you want to start building a function you can check if a module is available on the given system with:

Get-Module -Name <ModuleName> -ListAvailable

You can wrap this in a loop with an If block to cover multiple modules:

ForEach( $Module in $RequiredModules ) 
{
    If ( !(Get-Module -ListAvailable -Name $Module) ) {
        # find, install and load the module.
    }
}

I would draw your attention to the other *Module cmdlets to build out the remaining functionality you described.

Find-Module

Install-Module

Save-Module

Import-Module

  • Related