0

I want to use Implicitly Importing while using the PowerShell Module Az. This module has quite a lot of submodules and I don't want to import the specific version at the start of the script because of time. The script will run on an agent, which is not controlled by me, so that it could be, that a newer Az Module will be installed without my knowledge. If so, my script should still use the older version with Implicitly Importing. But I did not find a way to load older version in this way. It is always, that the newest version is used by Implicitly Importing. I could then overwrite it by importing the older version (like in the example below), but this is exactly what I don't want to do.

PS > Get-Module Impl*
PS > GetImplicitValue()
Implicit Importing from V2
PS > Get-Module Impl*

ModuleType Version    PreRelease Name                                ExportedCommands
---------- -------    ---------- ----                                ----------------
Script     2.1.2                 ImplicitlyImporting                 GetImplicitValue

PS > Import-Module ImplicitlyImporting -Force -RequiredVersion 1.0.2
PS > GetImplicitValue()
Implicit Importing from V1
PS > Get-Module Impl*

ModuleType Version    PreRelease Name                                ExportedCommands
---------- -------    ---------- ----                                ----------------
Script     1.0.2                 ImplicitlyImporting                 GetImplicitValue
Script     2.1.2                 ImplicitlyImporting                 GetImplicitValue

Any idea? Thanks in advance.

Boologne
  • 175
  • 1
  • 11

1 Answers1

1

Implicit implies importing the newest version, so you do not want to implicitly import when an older version may be required.

You can reduce the amount of time to import the Az module by specifying the submodule(s) you want:

# takes 0.8 seconds for two modules
Import-Module Az.Accounts -RequiredVersion 2.8.0
Import-Module Az.Security -RequiredVersion 1.3.0

# takes 70 seconds for 76 modules
Import-Module Az

Otherwise, you can check for and explicitly specify a version to load:

# Check if Az is already loaded, and what version
$loaded = Get-Module az
if ($loaded) {
  if ($Loaded.Version -eq [System.Version]'8.0.0') {'Az loaded and correct version'}
  else {'Wrong version of Az loaded'}
}

# If not loaded, then check if Az is installed, and what versions
if (-not (Get-Module az)) { 

  # check which Az is installed
  $installed = Get-InstalledModule az -AllVersions

  # import correct module version
  if ($installed.Version -eq [System.Version]'8.0.0') {
    'Correct Version Installed'
    Import-Module Az -RequiredVersion 8.0.0
  }

  else {
    Write-Error 'Required version of Az not installed'
    break
  }
}

As you saw with the answer here, you must explicitly import a module or its commands to use a specific version

Cpt.Whale
  • 4,784
  • 1
  • 10
  • 16