Welcome to the basics! In this chapter, we will start things off at the ground level. Basic PowerShell tasks will be covered so that you learn some basic concepts before going into more complex tasks. Before attempting any exercises covered in this book, you should first complete the ones covered in this chapter.
In this chapter, we will cover the following topics:
- Installing Azure PowerShell
- Deploying a virtual machine (VM)
- Resizing a VM with PowerShellÂ
- VM power states
- Basic management tasks
At the end of this chapter, you will have the opportunity to practice what you've learned by completing a hands-on exercise that covers many of the basic tasks covered in this chapter.Â
Performing management tasks within an Azure tenant, using PowerShell, requires a handful of prerequisites to be met first. For example, the AzureRM PowerShell module needs to be installed so that Azure PowerShell commands become available. However, since the preferred method of installing the AzureRM module is to do so via the PowerShell Gallery, the latest version of PowerShellGet
needs to be installed first.
Once the latest versions of PowerShellGet
and AzureRM are installed, the AzureRM module can be loaded and used to connect to the Azure tenant. The next few exercises will walk you through the installation of PowerShellGet
, how to use it to download and install AzureRM, and then how to use AzureRM to connect to an Azure tenant.
Before using PowerShell to deploy and manage virtual machines in Azure, you will need to install the Azure PowerShell module (AzureRM) on your workstation. The best way to install Azure PowerShell is to do it from the PowerShell Gallery, which is what you will learn to do in this section, starting with the installation of PowerShellGet
.
The installation of PowerShellGet
is necessary because PowerShellGet
is the tool that is used to pull down PowerShell modules from the galleryâso, before doing anything, you need to ensure that you have the latest version of the PowerShellGet
module (https://www.powershellgallery.com/) installed on your workstation. To check what version of PowerShellGet
you have, run the Get-Module
 command, which is shown as follows:
Get-Module ` -Name PowerShellGet ` -ListAvailable | Select-Object -Property Name,Version,Path
The Get-Module
 command will list what versions of PowerShellGet are currently available on your workstation. By piping the results of the Get-Module
 command (using the |
character) to the Select-Object
 command, you can view just the info you are looking for. In this case, you can see the Name
, Version
, and Path
of each instance of PowerShellGet
that currently resides on your machine:

To perform the exercises in this book, you are going to need PowerShellGet
version 1.1.2.0 or later installed. If you don't have PowerShellGet
version 1.1.2.0 or later installed, update it by running the Install-Module
 command, shown as follows:
Install-Module PowerShellGet -Force
The Install-Module
 command will update your PowerShellGet
module to the latest version. Specifying the -Force
 switch simply suppresses any Are you sure?
confirmation type messages. The following screenshot shows the installation of PowerShellGet
:

Once the latest version of PowerShellGet
is installed, you can install Azure PowerShell.
Before using PowerShellGet
to download and install Azure PowerShell, you must first configure your PowerShell environment with an execution policy that allows scripts to run. Since the default execution policy for PowerShell is Restricted
, you must change it by running the Set-ExecutionPolicy
 command:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
Running the Set-ExecutionPolicy
 command, to set the execution policy to RemoteSigned
, is sufficient for installing Azure PowerShell from the PowerShell Gallery. You could also set your policy to Unrestricted
, but that would further open you up to unsigned commands that could be malicious. As you can see in the following screenshot, PowerShell will prompt you to confirm that you wish to change the execution policy:

Once your execution policy is set to RemoteSigned
, you can install the AzureRM PowerShell module by running the Install-Module
 command:
Install-Module -Name AzureRM -AllowClobber
Running the preceding command launches the process of connecting to the PowerShell Gallery and downloading the Azure PowerShell module. The AllowClobber
switch ensures that you get the full and complete installation of AzureRM.
As you can see in the following screenshot, the PowerShell Gallery is not configured as a trusted repository for PowerShellGet
(you'd think it would be trusted by default). As such, you are likely to see a warning about the repository not being trusted, and you will be prompted whether you are sure you want to download the module. It's safe to answer Yes
, or Yes to all
, when you see this prompt.
Selecting Yes
allows the installation of Azure PowerShell to continue:

The installation of Azure PowerShell is generally painless. The AzureRM module that gets installed is a rollup module for the Azure Resource Manager cmdlets
. Installing the AzureRM module also pulls down, from the PowerShell Gallery, any Azure PowerShell module not previously installed.
Once the Azure PowerShell module (AzureRM) has been installed, you can load the module into your PowerShell session using the Import-Module
 command. As per Microsoft's recommendations, you should do this in a non-elevated PowerShell session, so if you haven't done so already, open a new non-elevated PowerShell session and, from within this session, run the following command:
Import-Module -Name AzureRM
Importing the Azure PowerShell module is rather uneventful. However, rest assured that, unless an error message is displayed, you now have Azure PowerShell loadedâand now that you have Azure PowerShell installed and loaded, you can now actually connect to Azure using PowerShell.
Although Azure PowerShell supports multiple login methods, the easiest way to get logged in is interactively at the command line, using the Connect-AzureRMAccount
 command. It's a simple command to run:
Connect-AzureRmAccount
After hitting Enter, a dialog box prompts you for your Azure admin credentials. Go ahead and supply your Azure admin credentials. Once you've supplied those credentials, you will be connected to your tenant:

To confirm that you are connected to your Azure tenant, you can run the Get-AzureRmSubscription
 command from PowerShell to confirm that it returns your subscription information:
Get-AzureRmSubscription
If the preceding command returns your subscription info, you can move on to the next steps.Â
The objective of this section is to walk you through the process of deploying a VM in Azure, using PowerShell. Topics covered in this section include the provisioning of a resource group and the deployment of a VM.
Since the deployment of a VM in Azure, using PowerShell, requires quite a few switches to be specified, each switch will also be explained in detail.
Before deploying a VMÂ in Azure with PowerShell, you need to first create a resource group into which the VM will be deployed. An Azure resource group, by the way, is a logical container into which Azure resources are deployed and from where they are managed. Deploying a resource group is rather easy; it is completed with just a single PowerShell command.
To provision a group, you just need to run the New-AzureRMResourceGroup
 command. When running the command, you need to specify a name for the resource group and a location for it:
New-AzureRmResourceGroup -ResourceGroupName "VMLab" -Location "EastUS"
In the preceding example, I'm specifying the ResourceGroupName
 and Location
 switches. The preceding command creates a resource group called VMLab
 and it creates it in the EastUS
 location:

Running the New-AzureRMResourceGroup
 command takes just a moment or two and, once the command completes, you can visit the Azure dashboard to confirm that the resource group has been created. Instead, you can run the Get-AzureRmResourceGroup
 PowerShell command without any switches, to ensure that the new resource group is listed.
To confirm that your new VMLab
resource group has been created, run the following command:
Get-AzureRmResourceGroup
Upon running the preceding command, you should see a resource group called VMLab
listed. Before continuing with the next exercises (if you are following along), be sure that youâve created a resource group, called VMLab
.
When creating a VM, several options are available to youâincluding OS image, network configuration, and administrative credentials. However, a VM can also be created with default settings, using a minimal configuration.
The process of provisioning a VM consists of two different PowerShell commands. The first command, called Get-Credential
, allows you to specify local administrator credentials for the VM. Once those credentials have been established, you can run the New-AzureRmVm
 command to configure and deploy a VM.
To create a local admin account and password for the VM being deployed, run the following command:Â
$cred = Get-Credential
This command results in a prompt, to which you can respond, by supplying a local admin account login and associated password. The login information provided in the prompt is then used by the VM deployment process to provision a local admin for the VM when it is deployed:

Running the $cred = Get-Credential
Â
command stores the local admin credentials that you provide in the $cred
 variable. After creating the local admin credentials, you can run the New-AzureRmVm
 command to provision the VM.Â
The $cred
 variable is referenced during the provisioning process, so that when the VM is provisioned, the local admin info that was provided is used.
To provision a new VM, run the entire following command in a PowerShell session:
New-AzureRmVm -ResourceGroupName "VMLab" ` -Name "myVM" ` -Location "EastUS" ` -VirtualNetworkName "myVnet" ` -SubnetName "mySubnet" ` -SecurityGroupName "myNSG" ` -PublicIpAddressName "myPublicIP" ` -Credential $cred
The preceding command is a single-line command. Although the command itself is broken up into multiple lines, this command is one long command when written out.
To break the command up into multiple lines so that I can better explain it, I used the tick symbol (Â `
 ) to let PowerShell know it's one long command, despite being supplied over multiple lines.
If you prefer the copy/paste approach, visit mybook.thomasmitchell.net for an online version of all the commands in this book:

The tick symbol tells PowerShell that even though I'm supplying a multi-line command, it should be interpreted as a single-line command instead.
With that said, let's go through the command, line by line.
As you can see from the preceding command (which takes about 10-15 minutes to run), New-AzurermVM
 requires some basic information to provision a VM.
The ResourceGroupName
 switch tells the command which resource group the VM should be deployed to. In this case, the VM is going to be deployed into the VMLab resource group that was provisioned earlier (if you are following along with these instructions). The Name
 switch specifies the name of the VM being deployed. In this example, the VM is going to be called myVM
.
The new VM is deployed into the EastUS
region by specifying the Location
 switch.
Since the VM needs to go onto a network and subnet, this command includes the VirtualNetworkName
 switch and SubnetName
 switch. In the preceding example, the VM is being deployed to a virtual network called myVNet
and a subnet called mySubnet
. Because we haven't created a virtual network yet, nor a subnet, the New-AzureRmVM
 command is going to create them automatically, using default IP range values. Had we previously provisioned a virtual network and virtual subnet, we could specify their names instead, and the VM would be deployed to them.
To protect the VM, a network security group needs to be deployed. To provision and associate a network security group with the new VM, the SecurityGroupName
 switch is used. In the preceding example, the network security group is called myNSG
. As was the case with the virtual network and virtual subnet, had we pre-provisioned another security group, we could have specified that group with the SecurityGroupName
 switch.
To be able to RDP to the new VM over the internet from a workstation, we need to give the VM a public IP address. This is done with the PublicIPAddressName
 switch. In this example, the public IP address resource is called myPublicIP
.Â
Note
In a production environment, assigning a public IP address and enabling RDP for a VM is a terrible practice. You never want to make RDP available over the internet on a production machine. Iâm simply enabling RDP in this case for ease of use, so I can more easily work through the deployment process.
With that PSA out of the way, we must tell the New-AzureRmVm
 command what local admin credentials to provision for this VM. To do this, I'm specifying the Credential
 switch and referencing the $cred
 variable with it.
With all this information provided, running the New-AzureRmVm
 command will deploy a default Windows 2016 Server into the EastUS region, onto a new subnet called mySubnet, which is part of a virtual network called myVnet
. The VM will be protected by a default set of rules contained in a network security group called MyNSG
.
The VM deployed with the preceding command is called myVM
and it will be deployed into a resource group called VMLab
. It will assign a dynamic public IP address that is accessible from the internet and the local admin account, which will match what was configured when we ran the Get-Credential
 command:

The VM deployment process can take several minutes to complete, but when it does, you will have a fully functioning virtual machine deployed.
Once the deployment is complete, you can confirm in the Azure dashboard that the VM is up and running. You can also run the following command instead:
Get-AzureRmVm -resourcegroup VMLab -name MyVM -status
The output of the preceding command will show the status of your newly deployed VM.
Since the intention of this book is to explain how to deploy and manage VMs using PowerShell, it makes sense to explain how to RDP to a VM from PowerShell.
Once a VM is deployed, you can create a remote desktop connection with the VMÂ right from a PowerShell session. To do so, you need to run two commands.
First, you need to track down the public IP address of the VM by running the Get-AzureRmPublicIpAddress
 command. This command will display the public IP address of the VM. You can then use that IP to connect to the VM.
To obtain the IP address of the MyVM
VM deployed in the preceding example, run the following command:
Get-AzureRmPublicIpAddress ` -Name myPublicIP ` -ResourceGroupName VMLab | Select IPAddress
The Get-AzureRmPublicIpAddress
 command displays the public IP address for the VM. All you have to do is tell the command which public IP resource you want to query and then pipe that data to a Select
statement:

The output is the public IP address of the VM.
To connect to the VM via RDP, you can run the mstsc.exe
 command right from the PowerShell session and replace publicIpAddress
 with the IP address of the VM:
mstsc.exe /v:publicIpAddress
In the Windows Security window, supply the local username and password that you created for the VM and then click OK
:

The RDP client session will launch and then you can log into the newly provisionedVM. Logging into the new virtual machine from this point forward is no different from any other RDP session.
There will be times when an application will require more resources than it once did. In cases such as these, an Azure VM can be resized.Â
Resizing a VM requires the use of two different PowerShell commands. The first command, called Get-AzureRmVMSize
, is used to retrieve a list of VM sizes available in a chosen region. Before resizing a virtual machine, you must ensure that whatever size you want to change the virtual machine to is available in the virtual machine's region. The Get-AzureRmVMSize
 command does exactly this.
The second command that is required the Update-AzureRmVM
 command. This command is used to update a VM after changing its size configuration.
In this section, you are going to resize the myVM
virtual machine that you created earlier. However, before attempting to do so, you will need to retrieve a list of VM sizes available in the EastUS
region, which is where the myVM
virtual machine resides.
To complete this task, run the following command from PowerShell:
Get-AzureRmVMSize -Location "EastUS"
The preceding command should return quite a few sizes. Confirm that Standard DS2_V2
is available. If it's not, find another size that is available.
After confirming that Standard DS2_V2
(or your chosen size) is available, you can use PowerShell to resize the myVM
virtual machine:

Â
After confirming that Standard DS2_V2
is available in the EastUS
region, you also need to make sure that it's available on the current cluster where the myVM
virtual machine resides. To do so, use the same Get-AzureRmVMSize
 command as beforeâjust with a few different switches.
To confirm that the Standard DS2_V2
size (or your chosen size) is available on the cluster where myVM
resides, run the following command:
Get-AzureRmVMSize -ResourceGroupName "VMLab" -VMName "myVM"
By specifying the -VMName
 and -ResourceGroupName
 switches in the preceding command, you can confirm that the Standard DS2_V2
size is available on the same cluster as the VM. If so, the virtual machine can be resized from a powered-on state (without the need to deallocate it). However, it will still require a reboot during the operation:

If the Standard DS2_V2
size is not available on the VM's current cluster, the virtual machine needs to first be deallocated before the resize operation can occur. In such a case, any data on the temp disk is removed and the public IP address will change (unless a static IP address is being used).
To resize the virtual machine (myVM
), you need to run a few different PowerShell commands.
The first command essentially loads the configuration profile of the VM into a variable called $vm
. The second command will modify the -VMSize
 attribute stored in that variable to reflect the new VM size. The third command, called Update-AzureRmVM
, will take the updated configuration that is stored in the $vm
 variable and write it to the VM.
To begin the resize process of the myVM
virtual machine, run the following command from a PowerShell session that's connected to your Azure tenant:
$vm = Get-AzureRmVM -ResourceGroupName "VMLab" -VMName "myVM"
The preceding command retrieves the current VM information and stores it in the $vm
 variable.
To modify the size attribute for the VM, run the following command:
$vm.HardwareProfile.VmSize = "Standard_DS2_V2"
The previous command changes the size
attribute of the myVM
virtual machine that's stored in the variable to Standard DS2_V2
.
Once the new size has been specified using the preceding command, run the following command to update the VM:
Update-AzureRmVM -VM $vm -ResourceGroupName "VMLab"
After executing the preceding Update-AzureRmVM
 command, the myVM
virtual machine is updated and then automatically restarted:

The process takes a few minutes to complete, but when it completes, the myVM
virtual machine is resized to reflect the new size.
If you manage any number of Azure VMs on a day-to-day basis, you are going to need to understand the different states in which VMs can exist. In this section, I want to briefly touch on the available power states for a VM, and on how to check the current power state of a VMe via PowerShell.
There are seven power states that a VMÂ can exist in:
- Starting:Â Indicates that the VM is being started.
- Running: Indicates that the VM is running.
- Stopping:Â Indicates that the VM is being stopped.
- Stopped:Â Indicates that the VM is stopped. Note that VMs in the stopped state still incur compute charges.
- Deallocating:Â Indicates that the VMÂ is being deallocated.
- Deallocated:Â Indicates that the VMÂ is completely removed from the hypervisor but still available in the control plane. VMs in the deallocated state do not incur compute charges.
- Unknown (
-
):Â Indicates that the power state of the VM is unknown.
Although most of these are self-explanatory, I wanted to ensure that you were aware of them.
Retrieving the status of a VM is rather straightforward. To retrieve the state of a specific virtual machine, use the Get-AzureRmVM
 command, taking care to specify valid names for the VM and the resource group.
Run the following command to check the status of the myVM
virtual machine:
Get-AzureRmVM ` -ResourceGroupName "VMLab" ` -Name "myVM" ` -Status
The command in the preceding example retrieves the current status of the myVM
virtual machine. While the output will include quite a bit of information, what we are most concerned about for this exercise is the part that shows whether the VM is running:

The resulting output indicates the current status of the VM.
Day-to-day operations will often require you to perform several management tasks, such as starting, stopping, and deleting vVMs. In addition, you may find yourself in situations where you will need (or want) to create scripts to automate certain VM tasks.
By becoming familiar with how to use Azure PowerShell, you can script and automate many common management tasks that would otherwise require manual intervention.
The five main commands I'm going to cover in this section are Stop-AzureRmVM
, Start-AzureRmVM
, Restart-AzureRmVM
, Remove-AzureRmVM
, and Remove-AzureRmResourceGroup
.
To stop an Azure VM, you can use the Stop-AzureRmVm
 command. Go ahead and run the command to stop the myVM
virtual machine:
Stop-AzureRmVm -ResourceGroupName "VMLab" -Name "myVM" -Force
The only switches required in the preceding command are the ResourceGroupName
 switch and the Name
 switch. The Force
 switch is optional, but it shuts down the VM without asking for confirmation.Â
Another optional switch (not shown) is the StayProvisioned
 switch. If you wish to stop a VM but keep the virtual machine allocated, you could specify the StayProvisioned
 switch as well. Keep in mind that if you do this, you will continue to be charged for compute cycles even though the VM is off.
Once you've stopped the myVM
virtual machine, run the Get-AzureRmVM
 command to confirm the status of it:
Get-AzureRmVM ` -ResourceGroupName "VMLab" ` -Name "myVM" ` -Status
The preceding command will display the status of the myVM
virtual machine and should show the status as Deallocated
:

In the next section, you will start the myVM
virtual machine, using the Start-AzureRmVM
 command.
To start a VM, you can use the Start-AzureRmVM
 command. Run the following command to start the myVM
virtual machine:
Start-AzureRmVM -ResourceGroupName "VMLab" -Name "myVM"
The preceding command starts the myVM
virtual machine in the VMLab
resource group.
Check the status using Get-AzureRmVM
 as before:
Get-AzureRmVM ` -ResourceGroupName "VMLab" ` -Name "myVM" ` -Status
The preceding command will display the status of the myVM
virtual machine.
To restart a VM, you can use the Restart-AzureRmVM
 command. Run the following command to restart the myVM
virtual machine:
Restart-AzureRmVM -ResourceGroupName "VMLab" -Name "myVM"
The preceding command restarts the myVM
virtual machine in the VMLab
resource group.
Check the status using Get-AzureRmVM
:
Get-AzureRmVM ` -ResourceGroupName "VMLab" ` -Name "myVM" ` -Status
The preceding command will display the status of the myVM
virtual machine.
There will be times when you need to decommission a VM. Doing so is performed with the Stop-AzureRmVM
 command. However, before deleting a VM, it should first be stopped. In this example, we'll stop the myVM
virtual machine and then delete it.
To stop the VM, run the following command:
Stop-AzureRmVM -ResourceGroupName "VMLab" -Name "myVM" -Force
Once the VM is stopped, run the preceding Remove-AzureRmVM
 command to delete the VM:
Remove-AzureRmVM -ResourceGroupName "VMLab" -Name "myVM"
As was the case with the stop and start commands, only the ResourceGroupName
 and Name
 switches need to be provided:

After a few minutes, run the following command to see whether the myVM
virtual machine has been deleted:
Get-AzureRmVM -status
If you've successfully deleted the VM, it should not be shown in the output of the preceding command.
The only hassle with the Remove-AzureRmVM
 command is that it only removes the VM. It does not clean up other resources that are attached to the VM, such as NICs or additional disks. They need to be cleaned up manually, unless you opt to script their removal.
The final command that I want to cover is the Remove-AzureRmResourceGroup
 command. This command removes an entire resource group. I personally use it quite regularly, since I'm always creating lab-and course-specific resource groups. Once I'm done with the labs and courses, I just delete the resource groups so that all resources inside the resource groups in their entirety are removed simultaneously. This makes my life easier.
To remove the entire VMLab
resource group, run the Remove-AzureRmResourceGroup
 command. Don't worry; we'll be re-creating it later in this book:
Remove-AzureRmResourceGroup -Name "VMLab" -Force
Running this command tells Azure to delete the VMLab
resource group and everything inside it. The Force
 switch suppresses the are you sure
prompts.
Although this command can sometimes take a while to complete, when it does complete, the entire resource group is removed, along with everything inside of it.
After running the preceding command (and waiting a few minutes), run the following Get-AzureRmResourceGroup
 command to confirm that the VMLab
resource group is gone:
Get-AzureRmResourceGroup -Name "VMLab"
Apply what you've learned in this chapter by completing the following project:
- Project:Â Common Commands
- Project goal:Â The goal of this project is to successfully deploy a VM and to practice stopping, starting, and removing it
- Key commands:
New-AzureRmResourceGroup
Get-AzureRmResourceGroup
New-AzureRmVm
Get-AzureRmVM
Stop-AzureRmVM
Start-AzureRmVM
Remove-AzureRmVM
Remove-AzureRmResourceGroup
- General steps:
- Create a resource group
- Deploy a VM with a default configuration
- Stop the VM
- Start the VM
- Delete the VM
- Delete the resource group and all its resources
- Validation:Â Ensure that the VM deploys, and that it stops and starts as expected
- Reference info: The Basic Management Tasks section
Congratulations! You've reached the end of this chapter. Here, we covered several basic skills.
You learned how to do the following:
- Install Azure PowerShell
- Deploy a VM
- Resize a VM with PowerShellÂ
- Manage VM power states
- Perform basic VM management tasks (start, restart, stop, and delete)
Now that you know how to perform some basic tasks, we'll move on to the next chapter, where we will work with images.