Last Update: Sep 24, 2024 | Published: Apr 01, 2014
To absolute beginners, PowerShell can look complex. And it is a more powerful tool than VBScript or other command line programs traditionally native to Windows. In this Ask the Admin, I’ll show you how to create a simple loop function to automatically run a series of commands to start or stop VMs running in Windows Azure.
The Windows Azure web-based management portal is a useful tool for beginners, but when cloud environments grow, trying to manage virtual machines using the management portal can be a pain. I wanted a quick way to make sure that all VMs in an Azure subscription were stopped and deallocated from the Azure fabric. It turns out that it is quite easy if all VMs are running in the same cloud service, but if they’re not, you need to create a simple PowerShell loop.
If all the VMs you want to start or stop are running in the same cloud service, you can use a wildcard to issue a command to all the VMs. For more information on using PowerShell to manage Windows Azure, see “Setup Windows Azure PowerShell Management” on Petri. (Related: [this_link_has_been_removed].)
The Start-AzureVM command will start all VMs in the contosodc1new cloud service with names beginning with contoso. The * is a wildcard that allows the command to match VMs with names starting with ‘contoso’. Despite only running the Start-AzureVM command once in this example, it will start multiple VMs matching the wildcard if they exist.
Unfortunately, it’s not possible to use a wildcard in the –ServiceName parameter when using the Start-AzureVM or Stop-AzureVM commands. To stop VMs running across different cloud services, you’ll need to enumerate all the services and create a loop to stop or start the VMs.
The above command will stop all running VMs in your Azure subscription and deallocate their associated resources from the Azure fabric.
To understand how this works, run through the following commands in the PowerShell console:
The Get-AzureService command in the loop above enumerates the cloud service information, and then the Foreach-Object loop pipes the results in turn to the Stop-AzureVM command using the $_.ServiceName variable.
Related Articles: