How to run scripts in your Azure VM by using Run Command

As you know, you can access your Azure virtual machine () in multiple ways, like SSH or . However, if you have issues with the or SSH network configuration, the Run Command feature is another option. Run Command can run a PowerShell or shell script within an Azure VM remotely by using the agent. This scenario is especially useful when you need to operating system network configurations or user access configuration.

You use Run Command for Azure VMs through the Azure portalREST API, Azure CLI, or PowerShell. Here are some examples:

Azure Portal

You can run commands directly from the Azure Portal. In the menu of the Azure VM, you can select Run command. Here you can find some predefined scripts to your Azure VM. In the case of a Windows VM, you will find scripts like configuring port or enable PowerShell remoting. But you can also run your custom PowerShell script.

Azure VM Run Command Run PowerShell ScriptAzure VM Run Command Run PowerShell Script

 For VMs, you will find predefined options to run a Linux shell script or ifconfig to list the network configuration.

Azure CLI

You also run commands directly from the Azure CLI. 

az vm run-command invoke -g myResourceGroup -n myVm --command-id RunShellScript --scripts "sudo apt-get update && sudo apt-get install -y nginx"

The az vm run-command CLI command works with Linux and Windows VMs. You can find more information about the Azure CLI option here.

Azure PowerShell

You can also use Azure PowerShell to use the run command capabilities to run PowerShell scripts against the guest agent inside the Azure VM. For that, you can simply use the Invoke-AzVMRunCommand cmdlet from the Az PowerShell module. You can also run this command directly from Azure Cloud Shell as well.

Invoke-AzVMRunCommand -ResourceGroupName '' -Name '' -CommandId 'RunPowerShellScript' -ScriptPath '' -Parameter @{"arg1" = "var1";"arg2" = "var2"}

The cmdlet expects the script referenced in the -ScriptPath parameter to be local to where the cmdlet is being run. If you are running it from your local machine, the script will need to be stored on your machine. If you are running the script from Cloud Shell, you will need to have the script available in your Cloud Shell. You can find more information about the Invoke-AzVMRunCommand PowerShell cmdlet option here.


The Run Command option is a great solution if you need to run scripts inside an Azure VM using the guest agent to network or access configurations. You can learn more about the Run Command here:

You can also find more information about the Azure Virtual Machine guest agent here:

I hope this blog post was helpful. If you have any questions or comments, feel free to leave a comment.


This article was originally published by Microsoft's ITOps Talk Blog. You can find the original article here.