How to run PowerShell cmdlets from custom PS modules when deploying a new Azure VM?

190 views Asked by At

Is it possible to install a custom PowerShell module in Azure VM post-deployment task and run PS cmdlets from that module in this task?

I have a Bicep template that deploys a new Windows Azure VM. The template has a Microsoft.Compute/virtualMachines/extensions@2020-12-01 post-deployment resource that takes these steps:

  1. Installs an MSI-packaged application (with a new custom PowerShell module) using Start-Process (OK)
  2. Creates several folders via PowerShell (OK)
  3. Runs several cmdlets installed at step 1 (NOT OK)

Running a cmdlet from the custom module in the post-deployment script shows the following error in the "Extensions + applications" log:

... is not recognized as the name of a cmdlet ...

When I change the post-deployment step to Import-Module MODULENAME, I see another message:

Import-Module : The specified module 'MODULENAME' was not loaded because no valid module file was found in any module \r\ndirectory.

When I run Get-Module in the post-deployment task, I see only these two modules listsd:

ModuleType Version    Name                                ExportedCommands                                             
---------- -------    ----                                ----------------                                             
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Con...
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}

So the module is not getting loaded.

But when I remote to the deployed VM, I run the cmdlets from the custom PowerShell module without any errors.

I think that my scenario is supported, but I don't quite understand how to troubleshoot this further.

1

There are 1 answers

0
bahrep On BEST ANSWER

I resolved the problem with these two steps:

  1. I've added -Wait to Start-Process and this has resolved the problem.
  2. I've added a path to the module into PSModulePath and ran $Env:PSModulePath = $Env:PSModulePath+";PATH-TO-MODULE" Import-Module MODULENAME -Force. Normally, the installed does this step for me. But it appears that I need to run these commands manually because all this is done in a single PowerShell session.

It appears that the problem was with my customScript.ps1 script. The very first line of the script installs an MSI-packaged application that adds the required PowerShell module:

Start-Process -FilePath msiexec.exe -ArgumentList @('/i', 'msi-installer-name.msi', '/qb')

PowerShell starts the installation using Start-Process and continues. So when I'm running these commands, the installation hasn't yet finished:

$env:PSModulePath | Out-File C:\Temp\psmodulepath.txt
Get-Module -ListAvailable | Out-File C:\Temp\getmodulelistavailable.txt