How do I import a PowerShell module for use by a pipeline task

Viewed 21093

I'm creating a Build Pipeline in Azure DevOps. I have a PowerShell task that invokes a script inside a file - it's not "inline" PowerShell. That script needs the Az.Accounts module so I added Import-Module Az.Accounts. When I run the pipeline, I get the following:

Import-Module : The specified module 'Az.Accounts' was not loaded because no valid module file was found in any module 
directory.
At D:\a\1\s\XXX\XXX\XXX.ps1:14 char:1
+ Import-Module Az.Accounts
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (Az.Accounts:String) [Import-Module], FileNotFoundException
    + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand

How do I add the missing module so my script can run?

3 Answers

By default, the hosted windows agent just include the AzureRM module, which is older.With the Az module, Azure PowerShell is now compatible with PowerShell 5.1 on Windows and PowerShell Core 6.x and later on all supported platforms - including Windows, macOS, and Linux.It is the biggest and most important change.

You can add an inline powershell task for installing the Az.Accounts module. enter image description here

Please note that if you don't add the -force parameter in the script, you will get this information in process.

User declined to install module (Az.Accounts).

The hosted agents don't have the Az modules installed -- they have the older AzureRM modules.

You should be able to use Install-Module to install them. Or you can rewrite your scripts to use AzureRM.

When using Azure Devops with the hosted windows-2019 image, I recommend you use the "AzurePowerShell" task instead of the plain "PowerShell" task, with a version @4 or higher.

documentation of this task can be found here.. Scroll down to see the options related to versioning.

Syntax and arguments are almost identical to the PowerShell task, except that you no longer need to login in Azure (you provide a service connection in the parameters).

You don't need to do crazy stuff like installing the Az module or uninstalling AzureRM. If you use the AzurePowerShell task, it's available for you.

note: don't use Az commands and AzureMR (deprecated) commands in the same script.

Related