Search code examples
powershellazure-automationazure-runbookimport-module

Prevent auto import of PowerShell modules in Azure Automation Runbook


I have an Azure Automation PowerShell runbook that calls particular child runbooks based on input parameters. The child runbooks perform actions with different PowerShell modules. I believe Azure Automation is automatically loading/importing the required modules at the moment the child runbook is called. I would like to prevent this behaviour, and import modules manually using import-module.

In an Azure Automation account, is it possible to control if/when required modules are imported?


Edit:
Microsoft documentation outlining conditions where modules are imported.


Solution

  • This behavior, in Powershell, is controlled by one of the preference variables. More specifically, the $PSModuleAutoloadingPreference variable.

    This variable control the automatic importing of module in the session. By default, it is set to All, which automatically import modules on first-use.

    Set this to None to disable the automatic importing of modules. You will need to explicitely use Import-Module for any command to be loaded.

    Here's a snippet of the official documentation regarding preferences variiables and that variable specifically.


    About Preference Variables

    PowerShell includes a set of variables that enable you to customize its behavior. These preference variables work like the options in GUI-based systems.

    The preference variables affect the PowerShell operating environment and all commands run in the environment. In many cases, the cmdlets have parameters that you can use to override the preference behavior for a specific command.

    ...

    $PSModuleAutoloadingPreference

    Enables and disables automatic importing of modules in the session. All is the default. To import a module, get or use any command in the module. For example, use Get-Command. The $PSModuleAutoloadingPreference variable does not exist by default. The default behavior when the variable is not defined is the same as $PSModuleAutoloadingPreference = 'All'.

    Regardless of the variable's value, you can use Import-Module to import a module.

    The $PSModuleAutoloadingPreference variable takes one of the PSModuleAutoLoadingPreference enumeration values: None, ModuleQualified, or All.

    Valid values are:

    • All: Modules are imported automatically on first-use.
    • ModuleQualified: Modules are imported automatically only when a user uses the module-qualified name of a command in the module. For example, if the user types MyModule\MyCommand, PowerShell imports the MyModule module.
    • None: Automatic importing of modules is disabled in the session. To import a module, use the Import-Module cmdlet.

    Source: about_Preference_Variables