As you know, you can access your Azure virtual machine (VM) in multiple ways, like SSH or RDP. However, if you have issues with the RDP 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 VM agent. This scenario is especially useful when you need to troubleshoot operating system network configurations or user access configuration.
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 troubleshoot your Azure VM. In the case of a Windows VM, you will find scripts like configuring RDP port or enable PowerShell remoting. But you can also run your custom PowerShell script.
Azure VM Run Command Run PowerShell Script
For Linux VMs, you will find predefined options to run a Linux shell script or ifconfig to list the network configuration.
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.
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.
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.
If you want to run it against multiple Azure VMs, check out my blog post here.
The Run Command option is a great solution if you need to run scripts inside an Azure VM using the guest agent to troubleshoot network or access configurations. You can learn more about the Run Command here: