Azure VM run commands

Azure VM run commands is a mechanism to run a PowerShell script inside a VM which is hosted on Azure. I need to perform some steps inside a Azure VM as a part of CI CD but I can’t open a connection to the VM for security reasons. In this case I find the Azure VM run commands is very useful. I use this to run a PowerShell script from my CI CD agent to the Azure VM.

There are three ways with which you can run a script inside the VM from outside without connecting to the VM. First is from Azure Portal, second is with Azure CLI and third is with Azure PowerShell. In my case I used Azure PowerShell.

You need to create a PowerShell script (.ps1) file which you need to run inside the VM. Then you need to login to Azure with Connect-AzAccount and use Invoke-AzVMRunCommand to run the command inside the VM.

I have created a PowerShell script file with name HelloUser.ps1.

    [Parameter(Mandatory = $true)]

Write-Host "Hello $UserName"

Then I have logged in to Azure.


After login I can use Invoke-AzVMRunCommand to run HelloUser.ps1 script inside the VM.

Invoke-AzVMRunCommand `
    -ResourceGroupName "vm-resource-group" `
    -Name "target-vm-name" `
    -CommandId "RunPowerShellScript" `
    -ScriptPath "HelloUser.ps1" `
    -Parameter @{"UserName" = "Jon"}

Read more about Azure VM run commands here.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s