Last Update: Sep 04, 2024 | Published: Jun 26, 2018
This post will show how to use the Run Command to execute PowerShell scripts inside an Azure virtual machine running Windows Server from the Azure Portal. Note that this can also be done using PowerShell, CLI, and REST API.
I often find myself in situations where I want to get something done with a virtual machine that I have access to via the Azure Portal but I haven’t got network access to it. I could configure network access and RDP into the virtual machine but that will either require time or an unwanted configuration change. I could use the Serial Access Console to log into the machine and get a PowerShell user interface but that’s more of a back door. What if I just want to run a one-off PowerShell script to get something done?
Microsoft added a new method for executing PowerShell scripts inside of a virtual machine in a simple, on-demand basis, called the Run Command. At any time, I can execute one of a set of supplied scripts or a custom script on one of several ways:
This method requires that you have a certain level of permissions for the virtual machine in question. You must have the Microsoft.Compute/virtualMachines/runCommand/action permission, which is available to administrators with Contributor or higher rights over the virtual machine resource.
You can find Run Command in the settings of a virtual machine under Operations.
Here you will find a number of scripts, with fairly self-explanatory names, that can be executed from the Azure Portal directly inside the guest OS of a Windows virtual machine running in Azure.
You can select one, such as IPConfig, and click Run. Note that you can view the script that will be executed. A minute or two later, the results of the script are displayed on screen.
You can also run a custom script. When you select the RunPowerShellScript option in the Azure Portal, a small script editor appears. You can type a small script in here or you can copy/paste in something (probably larger) from a more serious script editor such as PowerShell ISE or VS Code.
When you are ready to run, click the Run button and wait. Note that if you just want to send a PowerShell script file into a virtual machine to run, then use PowerShell on your PC:
Invoke-AzureRmVMRunCommand -ResourceGroupName 'petri' -Name 'vm-petri-01' -CommandId 'RunPowerShellScript' -ScriptPath 'myscript.ps1'
There are some restrictions when you use Run Command:
Some early feedback to Microsoft has found that Run Command requires that the virtual machine has some level of outbound connectivity to the Internet, probably to supply the output from an extension to Azure.