0% found this document useful (0 votes)
55 views

Azure PowerShell

Microsoft Azure is a comprehensive cloud computing platform by Microsoft, offering a variety of services including IaaS, PaaS, and SaaS for businesses of all sizes. Key features include global data center distribution, Azure Resource Manager for resource management, and a wide range of core services such as compute, storage, database, networking, AI, and security. The document also discusses Azure PowerShell for resource management and migration from AzureRM to the Az module for enhanced functionality.

Uploaded by

Mahmoud Elmahdy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

Azure PowerShell

Microsoft Azure is a comprehensive cloud computing platform by Microsoft, offering a variety of services including IaaS, PaaS, and SaaS for businesses of all sizes. Key features include global data center distribution, Azure Resource Manager for resource management, and a wide range of core services such as compute, storage, database, networking, AI, and security. The document also discusses Azure PowerShell for resource management and migration from AzureRM to the Az module for enhanced functionality.

Uploaded by

Mahmoud Elmahdy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Overview of Microsoft Azure and Its

Services
Microsoft Azure is a cloud computing platform developed by Microsoft, offering a broad
range of services for building, deploying, and managing applications through Microsoft's
globally distributed data centers. It provides solutions for infrastructure, platform, and
software needs, making it a versatile choice for businesses of all sizes.

Key Components of Azure


1. Cloud Computing Models in Azure

o Infrastructure as a Service (IaaS): Provides virtualized computing resources


over the internet. Examples include virtual machines (VMs) and network
management. Users can customize and control their own operating systems,
applications, and software while relying on Azure for infrastructure.

o Platform as a Service (PaaS): Offers a complete development and


deployment environment. It includes everything from servers and storage to
networking, databases, and application development tools, allowing
developers to build and manage applications without managing the
underlying infrastructure.

o Software as a Service (SaaS): Allows users to access applications hosted


by Azure on a subscription basis. Common examples include Office 365 and
other web-based applications managed entirely by Microsoft.

2. Azure Regions and Availability Zones

o Azure data centers are distributed globally, organized into regions and
availability zones to ensure data redundancy and service availability.

o Regions: Geographic locations where Azure resources are hosted, such as


“East US” or “West Europe.”

o Availability Zones: Data centers within a region that offer redundancy and
failover capabilities to keep applications running smoothly even if a data
center experiences issues.

3. Azure Resource Manager (ARM)


o Azure Resource Manager is a management layer in Azure that enables users
to create, update, and delete resources within their Azure accounts.
Resources can be organized in resource groups, making it easier to manage
related resources together.

o Resource Groups: Containers for resources, allowing you to manage and


control access, billing, and policies for groups of resources.

Core Azure Services


Azure offers a wide array of services that can be categorized into core groups to help users
design and build their applications. Below are some of the most popular Azure services:

1. Compute Services

o Virtual Machines (VMs): Provides IaaS virtual machines for running


applications and workloads, fully customizable by users.

o Azure App Service: A PaaS service for building and hosting web
applications, RESTful APIs, and mobile backends without managing
infrastructure.

o Azure Kubernetes Service (AKS): Manages containerized applications using


Kubernetes, simplifying deployment and scaling.

o Azure Functions: A serverless compute service that enables users to


execute code in response to events or triggers without managing servers.

2. Storage Services

o Azure Blob Storage: Offers scalable object storage for unstructured data,
such as images, videos, documents, and backups.

o Azure Disk Storage: Provides persistent, high-performance storage for VMs,


ensuring data retention even after the VM is stopped.

o Azure File Storage: A fully managed file share service that can be accessed
via SMB protocol, making it compatible with Windows and Linux systems.

o Azure Queue Storage: Allows for message-based communication between


different services or components of an application.

3. Database Services
o Azure SQL Database: A managed relational database service based on SQL
Server, ideal for storing structured data.

o Azure Cosmos DB: A globally distributed, multi-model database service with


low-latency access, suitable for scalable applications.

o Azure Database for MySQL, PostgreSQL, and MariaDB: Managed services


for popular open-source relational databases, enabling users to run these
databases without handling infrastructure.

o Azure Data Lake: A repository for storing large data sets, commonly used for
big data analytics.

4. Networking Services

o Virtual Network (VNet): Allows users to create isolated network


environments to securely connect VMs and other resources.

o Azure Load Balancer: Distributes incoming network traffic across multiple


resources to ensure high availability.

o Azure VPN Gateway: Establishes secure connections between Azure virtual


networks and on-premises networks.

o Azure DNS: A DNS service for hosting domain name services, allowing users
to manage their DNS zones in Azure.

5. AI and Machine Learning Services

o Azure Machine Learning: Provides an environment to train, deploy, and


manage machine learning models with ease.

o Cognitive Services: Offers pre-built AI models for vision, speech, language,


and decision-making.

o Azure Bot Service: A platform for building, testing, and deploying intelligent
chatbots that can interact with users across various platforms.

6. Analytics and Big Data Services

o Azure Synapse Analytics: A unified analytics platform for big data and data
warehousing, integrating Spark, SQL, and other data processing tools.

o Azure HDInsight: A managed service for open-source analytics frameworks


like Hadoop, Spark, and Kafka.
o Azure Databricks: A collaborative platform optimized for big data analytics
using Apache Spark.

o Azure Stream Analytics: A real-time analytics service that can analyze and
process high-volume streaming data from IoT devices or apps.

7. Internet of Things (IoT) Services

o IoT Hub: Centralizes communication between IoT devices and applications,


enabling secure and scalable device-to-cloud interactions.

o Azure Digital Twins: Models physical environments digitally, allowing users


to track and analyze real-world data.

o Azure Sphere: Provides an end-to-end security solution for IoT devices, from
hardware to cloud connectivity.

8. Security and Identity Services

o Azure Active Directory (Azure AD): An identity and access management


service for securing applications and services.

o Azure Security Center: A unified security management system for


monitoring and protecting Azure resources.

o Azure Key Vault: Safeguards cryptographic keys and secrets, ensuring


secure management of sensitive data.

o Azure Sentinel: A scalable security information and event management


(SIEM) solution for threat detection and response.

9. DevOps and Development Tools

o Azure DevOps: A suite of tools for managing the application lifecycle,


including CI/CD, testing, and version control.

o Azure DevTest Labs: A service for developers and testers to quickly create
virtual environments with reusable templates.

o GitHub Codespaces: A cloud-hosted development environment that


integrates with GitHub, enabling developers to code from anywhere.
Benefits of Using Azure
1. Scalability and Flexibility: Azure services can scale to accommodate growing
workloads and fluctuating demands, from startups to global enterprises.

2. Global Reach: Azure’s extensive network of data centers enables users to deploy
applications and store data close to their customers, minimizing latency.

3. Cost Efficiency: With pay-as-you-go pricing and reserved instances, Azure provides
cost-effective solutions for managing IT infrastructure and applications.

4. Security and Compliance: Azure is designed with security in mind, adhering to


industry standards, and offering built-in compliance for various regulatory
requirements.

5. Seamless Integration: Azure seamlessly integrates with other Microsoft products,


including Office 365, Dynamics, and Windows Server, enhancing productivity and
user familiarity.

Use Cases of Azure


• Web Hosting: Hosting scalable web applications using Azure App Services.

• Data Analytics: Analyzing and visualizing large datasets with Azure Synapse
Analytics and Power BI.

• Backup and Disaster Recovery: Using Azure Site Recovery and Backup to ensure
data safety and availability.

• IoT Applications: Managing IoT devices, collecting and processing data, and
building digital twin models with IoT Hub and Azure Digital Twins.

• Machine Learning and AI: Building and deploying intelligent models with Azure
Machine Learning and Cognitive Services.
Introduction
You can manage Microsoft Azure resources by using the Azure portal, which is usually the
most common way of administration. However, for some tasks, Azure PowerShell is more
convenient. In this module, you'll learn about the Azure PowerShell environment and the Az
module for Windows PowerShell. Also, you'll learn about ways to manage Microsoft Entra
ID by using PowerShell modules.

Review Azure PowerShell


Azure PowerShell is a module that you add to Windows PowerShell or PowerShell Core to
let you connect to your Azure subscription and manage resources. It provides a set of
cmdlets that you can use to manage and administer Azure resources directly from the
PowerShell command line. Azure PowerShell makes it easier to interact with Azure, but
also provides powerful features for automation. Azure PowerShell is written in .NET
Standard and works with PowerShell 5.1 on Windows and PowerShell 7.0.6 LTS, PowerShell
7.1.3, or newer on all platforms.

Azure PowerShell requires PowerShell to function. PowerShell provides services such as


the shell window and command parsing. The Azure PowerShell module adds the Azure-
specific commands.

You should use Azure PowerShell when you want to build automated tools that use the
Azure Resource Manager model. You can use it in your browser with Azure Cloud Shell, or
install it on your local Windows, Mac, or Linux machine. In both cases, you have two modes
to choose from. You can use Azure PowerShell in interactive mode, in which you manually
issue one command at a time, or in scripting mode, where you run a script that consists of
multiple commands.

Review the benefits of the Azure


PowerShell module
The Az PowerShell module is a set of cmdlets for managing Azure resources directly from
PowerShell. PowerShell provides powerful features for automation that you can use to
manage your Azure resources; for example, in the context of a continuous integration and
continuous delivery (CI/CD) pipeline.
The Az PowerShell module is the replacement for AzureRM and is the recommended
version to use for interacting with Azure. To keep up with the latest Azure features in
PowerShell, you should migrate to the Az PowerShell module.

Benefits of the Az PowerShell module


The Az PowerShell module features the following benefits:

• Security and stability:

o Token cache encryption

o Prevention of man-in-the-middle attack type

o Support for authentication with Active Directory Federation Services (AD FS)
in Windows Server 2019

o Username and password authentication in PowerShell 7

o Support for features such as continuous access evaluation

• Support for all Azure services:

o All generally available Azure services have a corresponding supported


PowerShell module

o Multiple bug fixes and API version upgrades since AzureRM

• New capabilities:

o Support in Cloud Shell and cross-platform

o Ability to get and use access tokens to access Azure resources

o Cmdlets for advanced Representational State Transfer (REST) operations


with Azure resources

The Az PowerShell module is based on the .NET Standard library and works with PowerShell
7 and newer on all platforms including Windows, macOS, and Linux. It's also compatible
with Windows PowerShell 5.1.
Az is the most current PowerShell module for Azure. You can log issues or feature requests
directly on the GitHub repository. You can also contact Microsoft support if you have a
support contract. Feature requests will be implemented in the latest version of Az. Critical
issues will be implemented on the last two versions of Az.

Install the Azure PowerShell module


The Azure Az PowerShell module is a rollup module. Installing it downloads the available Az
PowerShell modules and makes their cmdlets available for use. The Azure Az PowerShell
module works with PowerShell 7.x and newer versions on all platforms. Azure PowerShell
has no additional requirements when you run it on PowerShell 7.x and newer versions.

To check your PowerShell version, run the following command from within a PowerShell
session:

Before installing the Azure Az PowerShell module, you should set your PowerShell script
execution policy to RemoteSigned. You can do this by running the following command:
Methods to install the Az PowerShell
module
You can install the Azure Az PowerShell module by using one of the following methods:

• The Install-Module cmdlet

• Azure PowerShell MSI

• Az PowerShell Docker container

The Install-Module cmdlet


Using the Install-Module cmdlet is the preferred installation method for the Azure Az
PowerShell module. You should install this module for the current user only. This is the
recommended installation scope. This method works the same on Windows, macOS, and
Linux platforms. To install the Az module, run the following command from a local
PowerShell session:

Although PowerShell 7.x is the recommended version of PowerShell, and Install-Module is


the recommended installation option, you can also install the Az module within PowerShell
5.1 environment on Windows. If you're on Windows 10 version 1607 or higher, you already
have PowerShell 5.1 installed. You should also make sure that you have .NET Framework
4.7.2 or newer installed and the latest version of PowerShellGet. To install the latest
version of the PowerShellGet module within PowerShell 5.1, run the following command:
You can then install the Az module by using the same command you use in PowerShell 7.1.

Azure PowerShell MSI


In some environments, it isn't possible to connect to the PowerShell Gallery. In such
situations, you can install the Az PowerShell module offline, by downloading the Azure
PowerShell MSI package. Keep in mind that the MSI installer only works for PowerShell 5.1
on Windows.

To update any PowerShell module, you should use the same method used to install the
module. For example, if you originally used Install-Module, then you should use Update-
Module to get the latest version. If you originally used the MSI package, then you should
download and install the new MSI package.

Az PowerShell Docker container


It's also possible to run Azure PowerShell inside a Docker image. Microsoft provides Docker
images with Azure PowerShell preinstalled. The released images require Docker 17.05 or
newer. The latest container image contains the latest version of PowerShell and the latest
Azure PowerShell modules supported with the Az module.

To download the image and start an interactive PowerShell session, you should run the
following commands:

Starting to work with Azure PowerShell


To start working in the Azure PowerShell environment, you should first sign in with your
Azure credentials. This step is different from working in pure PowerShell. Your Azure
credentials are the same credentials you use to sign in to the Azure portal or other Azure-
based resources.

To sign in to Azure from Azure PowerShell, run the following command:


After running this command, you'll be prompted to sign in with your Azure credentials. After
you successfully authenticate to Azure, you can start using commands from the Az module
to manage your Azure resources.

Migrate Azure PowerShell from AzureRM to


Azure
Scripts created for the AzureRM cmdlets won't automatically work with the Az module. To
make the transition easier, the AzureRM to Az migration toolkit was developed. No
migration to a new command set is ever convenient, but it's important that you understand
how to transition to the Az PowerShell module.

The new cmdlet names have been designed to be easier to learn. Instead of using AzureRm
or Azure in cmdlet names, you use Az cmdlets. For example, the old cmdlet New-
AzureRMVm has become New-AzVm. However, migration is more than just becoming
familiar with the new cmdlet names. There are renamed modules, parameters, and other
important changes.

Before taking any migration steps, check which versions of AzureRM are installed on your
system. Doing so allows you to make sure scripts are already running on the latest release
and let you know which versions of AzureRM must be uninstalled.

To check which versions of AzureRM you've installed, run the following command:
The recommended option to migrate from AzureRM to the Az PowerShell module is to use
automatic migration. For this, you need to install the AzureRM to Az migration toolkit by
running the following command:

With the AzureRM to Az migration toolkit, you can generate a plan to determine what
changes will be performed on your scripts before making any modifications to them and
before installing the Az PowerShell module.

You can also use Microsoft Visual Studio Code to migrate your existing scripts. To do so,
you first need to install the Azure PowerShell extension for Visual Studio Code. Then, you
need to perform the following steps:

1. Load your AzureRM script in Visual Studio Code.

2. Open the command palette by selecting Ctrl+Shift+P.

3. Select the Migrate Azure PowerShell script.

4. Select the AzureRM source version.

5. Follow the recommended actions for each underlined command or parameter.

Review Microsoft Azure Active Directory


module for Windows PowerShell and Azure
Active Directory PowerShell for Graph
modules
Review Microsoft Graph PowerShell module
The Microsoft Graph module for Windows PowerShell provides cmdlets that you can use
for Microsoft Entra administrative tasks. These tasks include user management, domain
management, and configuring single sign-on. This topic includes information about how to
install these cmdlets for use with your directory.
The following list summarizes the key advantages of using the Microsoft Graph PowerShell
SDK.

• Access to all Microsoft Graph APIs: Microsoft Graph PowerShell is based on


Microsoft Graph API. The Microsoft Graph API includes, in addition to Microsoft
Entra ID, APIs from other Microsoft services like SharePoint, Exchange, and Outlook,
all accessed through a single endpoint with a single access token.

• Supports PowerShell 7: Microsoft Graph PowerShell module works with


PowerShell 7 and later. It's also compatible with Windows PowerShell 5.1.

• Cross-platform support: Microsoft Graph PowerShell module works on all


platforms including Windows, macOS, and Linux.

• Supports modern authentication: Microsoft Graph PowerShell supports the


Microsoft Authentication Library (MSAL) which offers more security. For example,
you can use Passwordless sign-in experiences.

• Supports external identities: Users from other Microsoft Entra tenants can
authenticate to services in your tenant with Microsoft Graph PowerShell.

• Uses least privilege: Microsoft Graph PowerShell permissions are NOT pre-
authorized and users must perform one-time request for app permissions
depending on their needs.

• Advanced queries: Microsoft Graph PowerShell supports rich, advanced queries


via eventual consistency. For example, you can get a near-instant count of all users
using advanced queries.

• Open source: Feature teams and the community can create great PowerShell
experiences and share them with everyone.

• Receives regular updates: Microsoft Graph PowerShell commands are updated


regularly to support the latest Graph API updates.

The easiest way to install the module is from the PowerShell Gallery. You can install the
module with the Install-Module cmdlet by running the following command:

You can also add beta features for Microsoft Graph SDK by running (not required):
Connecting to Microsoft Entra ID with PowerShell
If you want to connect to the Microsoft Entra service with the Microsoft Graph module for
Windows PowerShell, run the following command:

After running the previous command, you'll be prompted for your Microsoft Entra
credentials. You should use the credentials that you use to sign in to Microsoft 365 or your
Azure services. After you authenticate, you'll be able to use the cmdlets available for
Microsoft Entra management.
Create a new Azure virtual machine by
using Windows PowerShell commands
To create a new Azure virtual machine (VM) with PowerShell commands, you can use the
locally installed Windows PowerShell with Az module, or you can use the Cloud Shell
environment that's available in Azure portal. If you choose to use your locally installed
PowerShell, it's recommended that you use Windows PowerShell 7.1. You should also
install the Az module, so you can have Azure-related commands available. Also, when
using locally installed PowerShell, you first need to use the Connect-AzAccount command
to authenticate and connect to your Azure tenant. When you run this command in your
PowerShell environment, you'll be prompted to authenticate. You need to use credentials
from your Azure tenant, with privileges that allow you to create the resources needed for
Azure VMs.

To create an Azure VM, you need to perform the following tasks:

1. Create a resource group.

2. Create an Azure VM.

3. Connect to the Azure VM.

Create a resource group


An Azure resource group is a logical container into which Azure resources are deployed and
managed. You must create a resource group before you create a VM. In the following
example, a resource group named myResourceGroup is created in the West Europe
region:

The resource group is later used when creating or modifying a VM or the resources
attached to a VM.

Create an Azure VM
The New-AzVM cmdlet creates a VM in Azure. This cmdlet uses a VM object as input. Use
the New-AzVMConfig cmdlet to create a virtual machine object. When you're creating a
VM, several options are available, such as operating system image, network configuration,
and administrative credentials. You can use other cmdlets to configure the VM, such
as Set-AzVMOperatingSystem, Set-AzVMSourceImage, Add-AzVMNetworkInterface,
and Set-AzVMOSDisk.

Before you run the New-AzVM command, you need to specify the credentials that you'll
use to sign in to the newly created Azure VM. The credentials that you specify during this
process will be assigned with local administrative privileges on the VM you're creating. It's
easiest to store these credentials in a variable, before creating a new Azure VM. To do this,
run this command:

When you run this command, you'll be prompted to provide the username and password
for the Azure VM. These credentials will be stored in the $cred variable.

After you store administrative credentials, you need to define parameters for the new VM.
You don't need to provide all the parameters that New-AzVM supports. Most of them are
optional, and if you don't provide them, their default values will be selected. You can also
change most of these parameters later.

You can choose to provide VM parameters directly with the New-AzVM command, or you
can define these parameters in a variable, and then use this variable with the New-
AzVM command.

The following code depicts an example of defining VM parameters:

When you define VM parameters as the previous example depicts, you can then use the
following command to create a new Azure VM, based on these parameters:
Alternatively, you can also choose to provide VM parameters directly with New-AzVM as in
the following example:

Connect to the Azure VM


After a new Azure VM is created, you need to connect to it to verify the deployment. After
the deployment has completed, create a remote desktop connection with the VM.

Run the following commands to return the public IP address of the VM. Take note of this IP
address so you can connect to it with your browser to test web connectivity in a future step.

To create a remote desktop session with the VM, use the following command on your local
machine. Replace the IP address with the publicIPAddress of your VM. When prompted,
enter the credentials you used when creating the VM.

When you run this command, you'll be prompted for credentials to connect to the VM. In
the Windows Security window, select More choices, and then select Use a different
account. Enter the username and password you created for the VM, and then select OK.
After you connect to your Azure VM through Remote Desktop Protocol (RDP), you'll be able
to manage it the same way as any other computer.
Manage Azure virtual machines by using
Windows PowerShell commands
Besides using Windows PowerShell to create new Azure VMs, you can also use PowerShell
commands to manage, modify, and remove Azure VMs and the resources related to Azure
VMs. This topic covers some of the most common tasks for managing and modifying Azure
VMs with PowerShell.

Modifying VM sizes
The VM size determines the amount of compute resources such as CPU, GPU, and memory
that are made available to the VM. You should create VMs using a VM size that's
appropriate for the workload. If a workload increases, you can also resize existing VMs.

To review a list of VM sizes available in a particular region, use the Get-


AzVMSize command. For example:

After a VM has been deployed, you can resize it to increase or decrease resource
allocation. Before resizing a VM, check if the size you want is available on the current VM
cluster. The Get-AzVMSize command returns a list of sizes:

If your preferred size is available, you can resize the VM from a powered-on state; however,
it's rebooted during the operation. The following example depicts how to change VM size to
the Standard_DS3_v2 size profile:
Management tasks
During the lifecycle of a VM, you might want to run management tasks such as starting,
stopping, or deleting a VM. Additionally, you might want to create scripts to automate
repetitive or complex tasks. You can use Azure PowerShell to perform many common
management tasks by using the command line or scripts.

To stop and deallocate a VM with Stop-AzVM, you can run the following command:

To start a VM, you can run the following command:

If you want to delete everything inside of a resource group, including VMs, you can run the
following command:

Adding disks to Azure VMs


When you create an Azure VM, two disks are automatically attached to the VM:

• Operating system disk. These disks can be sized up to 4 terabytes and host the VM's
operating system.

• Temporary disk. These disks use a solid-state drive that's located on the same Azure
host as the VM. Temporary disks are highly performant and might be used for
operations such as temporary data processing.

You can add additional data disks for installing applications and storing data. You should
use data disks in any situation that requires durable and responsive data storage. The size
of the VM determines how many data disks can be attached to it.

To add a data disk to an Azure VM after you create it, you need to define disk configuration
by using the New-AzDiskConfig command. You then need to use the New-
AzDisk and Add-AzVMDataDisk commands to add a new disk to the VM, as the following
example depicts:

Manage Azure related storage by using


Azure PowerShell
You can use Azure PowerShell to manage Azure-related storage. Before you start managing
your storage, you should first create a storage account, if you don't have one. Usually,
storage accounts are created automatically when you create other Azure resources such
as Azure virtual machines (VMs).

You can create a standard, general-purpose storage account with locally redundant storage
(LRS) replication by using New-AzStorageAccount. Next, get the storage account context
that defines the storage account you want to use. When acting on a storage account,
reference the context, instead of repeatedly passing in the credentials. Use the following
example to create a storage account called mystorageaccount with LRS and blob
encryption, which is enabled by default.

Blobs are always uploaded into a container. You can organize groups of blobs the way you
organize your files on your computer in folders.

Set the container name, and then create the container by using New-AzStorageContainer.
Set the blob permissions to allow public access of the files. The container name in the
following example is quickstartblobs.
You can use the Set-AzStorageAccount cmdlet to modify an Azure Storage account. You
can use this cmdlet to modify the account type, update a customer domain, or set tags on
a Storage account.

For example, to set the storage account type you should use the following command:

To set custom domain for existing storage account, you can use the following command:

Manage Azure subscriptions by using Azure


PowerShell
Most Azure users will only ever have a single subscription. However, if you're part of more
than one organization or your organization has divided up access to certain resources
across groupings, you might have multiple subscriptions within Azure.

In Azure PowerShell, accessing the resources for a subscription requires changing the
subscription associated with your current Azure session. You can do this by modifying the
active session context, which is the information about which tenant, subscription, and user
the cmdlets should be run against. To change subscriptions, you need to first retrieve an
Azure PowerShell Context object with Get-AzSubscription, and then change the current
context with Set-AzContext.

The Get-AzSubscription cmdlet gets the subscription ID, subscription name, and home
tenant for subscriptions that the current account can access.

To get all Azure subscriptions active on all tenants, run the following command:
To focus on subscriptions assigned to a specific tenant, run the following command:

The Set-AzContext cmdlet sets authentication information for cmdlets that you run in the
current session. The context includes tenant, subscription, and environment information.

To set the subscription context, run the following command:

The next example depicts how to get a subscription in the currently active tenant and set it
as the active session:
Introduction
Imagine working for an organization that uses Azure Virtual Machines (VMs) to test its
Customer Relationship Management (CRM) software. You create these VMs from images,
including a web front-end and a SQL database.

During multiple testing iterations on a single VM, you notice that changes to configuration
files and the database lead to inconsistent results. In one instance, a bug erroneously
generated a phone call record without an associated customer in the database. This
orphaned record caused subsequent integration tests to fail, even after you fixed the bug.

Recognizing the frequency of these testing cycles, which occur multiple times per week,
you decide to deploy a new VM for each cycle to ensure the consistency and reliability of
your test environment. By developing PowerShell scripts for deployment, you streamline
the process, optimize workflow efficiency, and minimize errors through automation.

This module teaches you how to deploy and manage Azure resources using Azure
PowerShell. You learn how to use Azure PowerShell interactively for one-off tasks and how
to write PowerShell scripts to automate recurring tasks.

Decide if Azure PowerShell is the


appropriate tool for your tasks
Imagine you must select a tool to deploy and manage the Azure resources for your
Customer Relationship Management (CRM) system. For testing, you need to create
resource groups and virtual machines (VMs) for each test iteration.

You seek a tool that's easy for administrators to learn, yet powerful enough to automate the
installation and configuration of multiple virtual machines. With several tools available,
your goal is to find the best one for your administrators to script the deployment of the
entire cloud infrastructure efficiently.

What tools are available?


Azure offers three administration tools:

• Azure portal

• Azure PowerShell
• Azure CLI

These tools provide the same deployment and configuration capabilities, allowing you to
perform any task with any of the three. All are available on Windows, Linux, and macOS.
However, they differ in syntax, setup requirements, and support for automation.

The rest of this unit describes each of these tools and offers guidance on how to choose
the best one for your needs.

Azure portal
The Azure portal is a web-based interface that allows you to create, configure, and manage
the resources in your Azure subscription. As a Graphical User Interface (GUI), it offers a
user-friendly way to locate and manage resources, with wizards and tooltips to assist you
through complex management tasks.

However, Azure portal lacks automation capabilities for repetitive tasks. For instance, if you
need to set up 15 VMs, you must create each one individually, completing the wizard for
each VM. This approach can be time-consuming and error-prone for more complex tasks.

Azure PowerShell
Azure PowerShell is a collection of modules that provide PowerShell cmdlets for managing
Azure resources. It requires PowerShell, a command-line shell and scripting language.

For example, Azure PowerShell provides the New-AzVM cmdlet to create a virtual machine
in your Azure subscription. To use it, launch PowerShell and execute the following
command:

Azure PowerShell is available in two ways: inside a browser via Azure Cloud Shell or
through a local installation on Windows, Linux, or macOS. You can use PowerShell
interactively, running Azure PowerShell commands from PowerShell, or you can create and
execute scripts that consist of multiple commands.

Azure CLI
The Azure CLI is a cross-platform command-line tool that enables you to manage Azure
resources. For instance, you can create a virtual machine using the following command
(this example uses Bash line continuation characters):

The Azure CLI is also available in two ways: inside a browser via Azure Cloud Shell or
through a local installation on Windows, Linux, or macOS. You can use it interactively by
launching a shell (such as Bash, PowerShell, or cmd.exe) and entering commands at the
prompt. Alternatively, you can automate repetitive tasks by assembling the commands into
a shell script using the syntax of your chosen shell.

How to choose a management tool


With few exceptions, any task you can perform in the Azure portal can also be
accomplished using Azure PowerShell or the Azure CLI. Here are some factors to consider
when choosing the most appropriate tool for your needs:

• Automation: Do you need to automate complex or repetitive tasks? Azure


PowerShell and the Azure CLI support automation, whereas the Azure portal
doesn't.

• Learning curve: Do you need to complete a task quickly without learning new
commands or syntax? The Azure portal is user-friendly and doesn't require learning
commands or syntax. In contrast, Azure PowerShell and the Azure CLI require an
understanding of command shell syntax and the specific requirements for each
command.

• Team skillset: Does your team have existing expertise? For instance, if your team is
already using PowerShell to manage other products like Windows, Exchange Server,
or Microsoft 365, they might find Azure PowerShell to be a more comfortable and
efficient choice.

Example
Let's revisit the scenario of choosing an administrative tool to deploy and test your CRM
application. Your administrators have two specific Azure tasks to complete:

1. Create one resource group for each category of testing (unit, integration, and
acceptance).

2. Create multiple VMs in each resource group before each round of testing.

The Azure portal is a reasonable choice for creating resource groups. Since these tasks are
one-off, you don't need scripts to create them.

Most administrators first experience Azure through the Azure portal. The portal provides a
well-organized graphical interface for managing Azure resources, making it an excellent
starting point. However, the portal doesn't support automation, which is essential for
repetitive tasks like creating multiple VMs several times a week.

For automation in Azure, you have two options:

• Azure PowerShell

• Azure CLI

Both tools meet your needs, but Azure PowerShell might be the best choice if your team
has existing PowerShell knowledge.

In practice, businesses typically perform a mix of one-off and repetitive tasks, often using
both the Azure portal and a scripting solution. In your CRM example, creating resource
groups using the Azure portal and automating VM creation with Azure PowerShell is a
reasonable approach.

The remainder of this module assumes Azure PowerShell is your choice for an automation
tool.
Install Azure PowerShell
In this scenario, your administrators prefer executing scripts locally on their computers
rather than using Azure Cloud Shell. Since your team uses a mixture of Windows, Linux,
and macOS, your task is to ensure Azure PowerShell works across all these devices. This
empowers your administrators to manage and automate the Azure infrastructure for your
organization from their preferred operating system on their local computers.

What must be installed?


We'll review detailed installation instructions for some common platforms in the next unit,
but first, let's look at the two key components required for Azure PowerShell:

• The PowerShell language: The PowerShell language is available in two variants:

o PowerShell version 7: This version can be installed on Windows, Linux, and


macOS.

o Windows PowerShell 5.1: This version is preinstalled and only runs on


Windows.

• The Az PowerShell module: This module must be installed to add the Azure-
specific commands to PowerShell.

After installing the appropriate version of PowerShell, you can then install
the Az PowerShell module to start managing Azure resources.

How to install PowerShell


To install PowerShell on all platforms, use a package manager. The recommended package
manager varies by operating system and distribution.

Windows
On Windows, use the Windows Package Manager (winget) to install the latest stable
version of PowerShell 7.
Linux
The package manager on Linux differs based on the distribution. PowerShell is available in
the Microsoft repository, which you must add to your package manager.

The package manager on Linux differs based on the distribution. PowerShell is available in
the Microsoft repository, which you must add to your package manager.

Distribution Package manager

Debian, Ubuntu apt-get

Red Hat Enterprise Linux (RHEL) dnf or yum depending on your RHEL version

To install PowerShell on supported versions of Ubuntu Linux, use the Advanced Packaging
Tool (apt) and the Bash command line.

macOS
On macOS, use Homebrew to install PowerShell.

The Az PowerShell module


Azure PowerShell is the product name for the official Microsoft PowerShell module
containing commands for managing Azure resources.

The current version of the Azure PowerShell module for managing Azure resources is
named Az. It's the recommended PowerShell module for managing Azure resources with
PowerShell. It includes thousands of commands that control almost every aspect of Azure.
The Az PowerShell module is cross-platform.

You might find examples on the internet that use the AzureRM PowerShell module, which is
the previous generation of Azure PowerShell. It's deprecated, no longer maintained or
supported, and not recommended. Commands in the AzureRM PowerShell module use
the *-AzureRM* format.
You might also encounter an Azure PowerShell module named Azure, which is for
managing legacy Azure resources that use Azure Service Manager (ASM) APIs.
The Azure PowerShell module isn't recommended when creating new resources since ASM
is scheduled to retire soon.

Exercise - Install Azure PowerShell


In this unit, you learn how to determine the version of PowerShell installed on your local
machine and how to install the latest version. You also learn how to install
the Az PowerShell module.

Install PowerShell on Windows

Windows PowerShell is included with the Windows operating system. However, we


recommend installing the latest stable version of PowerShell 7 for use with Azure
PowerShell. Follow these steps to determine which version of PowerShell is installed:

1. In the System Tray Search Box, type PowerShell. You might see multiple shortcuts:

• PowerShell 7 (x64): 64-bit version of PowerShell 7 (recommended).

• Windows PowerShell: 64-bit version of Windows PowerShell, included with


Windows.

• Windows PowerShell (x86): 32-bit version of Windows PowerShell, included


on 64-bit versions of Windows.

• Windows PowerShell ISE: 64-bit Integrated Scripting Environment (ISE) for


writing Windows PowerShell scripts.

• Windows PowerShell ISE (x86): 32-bit ISE, included on 64-bit versions of


Windows.

If PowerShell version 7 isn't installed, open Windows PowerShell and use Windows
Package Manager (Winget) to install the latest stable version of PowerShell 7:

2.Determine the PowerShell version:


To open PowerShell version 7, select the PowerShell 7 (x64) shortcut. Run the following
command to check the version of PowerShell:

3.Set the PowerShell execution policy:

• Check the current execution policy:

If the execution policy is set to Restricted, change it to RemoteSigned or less restrictive:

Confirm the execution policy change:

You're prompted to confirm the change:

Enter Y or A, then press Enter.

Install the Az PowerShell module


The Az PowerShell module is available from a global repository called the PowerShell
Gallery. You can install the module on your local machine using the Install-Module cmdlet.
To install the latest version of the Az PowerShell module, follow these steps:

1. Open PowerShell version 7

2. Install the Az PowerShell Module:

This command installs the Az PowerShell module for your current user, which is controlled
by the Scope parameter.

• NuGet installation prompt:

The installation relies on NuGet to retrieve components. You might be prompted to


download and install the latest version of NuGet:

Enter Y and press Enter.

• Untrusted repository prompt:

By default, the PowerShell Gallery isn't configured as a trusted repository. You're


prompted to confirm that you want to install the module from an untrusted repository:
Enter Y or A, then press Enter.

You should now see the Az PowerShell module installing.

This process enables you to use the full range of Azure-specific cmdlets available in
the Az PowerShell module.

Create an Azure Resource interactively with


Azure PowerShell
In interactive mode, PowerShell allows you to enter and run commands immediately.

In the Customer Relationship Management (CRM) example, the goal is to create three test
environments, each containing virtual machines (VMs). Use resource groups to ensure the
VMs are organized into separate environments:

• Unit testing

• Integration testing

• Acceptance testing

Since you only need to create the resource groups once, using PowerShell interactively for
this task is a reasonable choice.

When you run a command in PowerShell, it matches the command to a cmdlet and
performs the requested action.

Example: How to create a resource group with Azure


PowerShell
Let's perform a common task: creating a resource group. Resource groups help you
manage related resources collectively, and creating a new resource group is often one of
the first tasks you perform when starting a new Azure solution.

Here are the three steps you need to follow:

1. Connect to your Azure subscription.

2. Create the resource group.


3. Verify the resource group was successfully created.

Each step corresponds to a different Azure PowerShell command.

Connect to Azure
When using a local installation of Azure PowerShell, you must authenticate before
executing any Azure PowerShell commands. The Connect-AzAccount cmdlet prompts you
for your Azure credentials and then connects to your Azure subscription.

To connect interactively, you don't need to specify any parameters:

This command opens a prompt for your Azure credentials and establishes a connection to
your Azure subscription.

Work with subscriptions


If you're new to Azure, you only have a single subscription. However, if you've been using
Azure for a while, you might have multiple subscriptions. Azure PowerShell allows you to
configure which subscription your commands are executed against.

You can only be active in one subscription at a time. Use the Get-AzContext cmdlet to
determine which subscription is currently active. If it's not the correct one, you can switch
subscriptions using the Set-AzContext cmdlet.

1. Get a list of all your subscriptions:


2. Check the current subscription you're logged into:

3. Change your active subscription:

If you need to look up the Subscription ID, you can find it in the output of the Get-
AzSubscription cmdlet.

Create a resource group


When creating resources in Azure, you place them into a resource group for management
purposes.

To create a resource group, use the New-AzResourceGroup cmdlet. You must specify a
name and a location, and the name must be unique within your subscription. The location
determines where the metadata for your resource group is stored, which can be important
for compliance reasons. Use the Get-AzLocation cmdlet to determine the available
locations.

The syntax for creating a resource group is:

List all resource groups


To retrieve a list of all resource groups in the active subscription, use the Get-
AzResourceGroup cmdlet.
For a more concise view, you can pipe the output to the Format-Table cmdlet:

You can also filter the output to show only a specific resource group:

Create an Azure Virtual Machine


Creating virtual machines (VMs) is a common task you can perform with Azure PowerShell.

The New-AzVM cmdlet is used to create a VM. This cmdlet has several parameters to
handle the extensive configuration settings for a VM. Most parameters have reasonable
default values, so you typically need to specify only five key items:

• ResourceGroupName: The resource group where the new VM is placed.

• Name: The name of the VM in Azure.

• Location: The geographic region where the VM is provisioned.

• Credential: An object containing the username and password for the VM


administrator account. Use the Get-Credential cmdlet to prompt for a username
and password and store them as a credential object.

• Image: The operating system image to use for the VM, typically a Linux distribution
or Windows Server.

Here's an example:
You can supply these parameters as a hash table with splatting for the New-AzVM cmdlet,
as shown in the previous example. Alternatively, you could supply the parameters directly
to the New-AzVM cmdlet or use other cmdlets to configure the virtual machine, such
as Set-AzVMOperatingSystem, Set-AzVMSourceImage, Add-AzVMNetworkInterface,
and Set-AzVMOSDisk.

For example, to supply the parameters directly to the New-AzVM cmdlet, use the following
syntax:

Example: Getting information for a VM


You can list the VMs in your subscription using the Get-AzVM command. This command
also supports retrieving a specific VM by specifying the Name parameter.

Store the results of Get-AzVM in a variable:

The contents of the $vm variable is an object you can interact with. For example, you can
make changes to this object and then push the changes to Azure using the Update-
AzVM command:
Using PowerShell in interactive mode is appropriate for one-off tasks. For example, you can
create and manage resource groups interactively if they're only created once during the
lifetime of a project. Interactive mode is often quicker and easier than writing a script for
tasks that are executed only once.
Exercise - Create an Azure Resource
interactively with Azure PowerShell
In the original scenario, you must create virtual machines (VMs) to test your Customer
Relationship Management (CRM) software. When a new build is available, you want to spin
up a new VM to test the entire installation experience from a clean image. Once testing is
complete, you can delete the VM.

Let's try the commands to create a VM.

Create a Linux VM with Azure PowerShell


Since you're using the Azure sandbox, you don't need to create a resource group. Instead,
use the existing sandbox resource group [sandbox resource group name]. Be aware of the
location restrictions.

Here's how to create a new Azure VM with Azure PowerShell:

1. Use the New-AzVM cmdlet to create the VM.

• Specify the sandbox resource group: [sandbox resource group name].

• Name the VM, following your organization's naming standards.

• Choose a location close to you from the list of available Azure sandbox
locations.

o westus2

o southcentralus

o centralus

o eastus

o westeurope

o southeastasia

o japaneast

o brazilsouth

o australiasoutheast
o centralindia

• Use the Ubuntu Linux image: Canonical:0001-com-ubuntu-server-


jammy:22_04-lts:latest.

• Use the Get-Credential cmdlet to set the VM administrator credentials.

• Add the OpenPorts parameter with port 22 for SSH access.

• Create a public IP address name for SSH sign-in.

2. Enter Credentials:

When prompted, enter a username and password, following the guidelines: passwords
must be 12-123 characters long and meet three of the following four complexity
requirements: lowercase characters, uppercase characters, digits, and special
characters (Regex match [\W_]). For more information, see Linux VM FAQ.

3. Wait for the VM creation:

The VM creation process takes a few minutes to finish.

4. Query the VM:

When complete, query the VM and assign the VM object to a variable ($vm).

5. View information about the VM:

To view information about the VM, display the contents of the variable.
Example output:

6. Inspect VM properties:

You can inspect complex objects through the member-access operator (.). For example,
to see the properties in the VMSize object associated with
the HardwareProfile section, run the following command:

Or, to get information on one of the disks, run the following command:

7. Get available VM sizes:

Pass the VM object into other cmdlets to get available sizes:


8. Get the public IP address:

Retrieve the public IP address to connect to the VM and store it in a variable.

9. Connect to the VM:

Connect to the VM with SSH using the IP address from the variable. For example, if the
username is bob, use the following command:

Sign out by typing exit.

Delete a VM
To try more commands, let's delete the VM. Follow these steps:

1. Shut down the VM:

Run the following command:

Enter Y and press Enter when prompted to continue.

2. Delete the VM:

Once the VM stops, delete it by running the Remove-AzVM cmdlet.


Enter Y and press Enter when prompted to continue.

3. List all resources in the resource group:

Use the Get-AzResource cmdlet to list all the resources in the resource group. The
results are piped to Select-Object to return specific properties:

You should see several resources, including disks, virtual networks, etc., that still exist:

The Remove-AzVM command only deletes the VM. It doesn't clean up any of the other
resources. To manually clean them up, follow these steps:

4. Delete the network interface:

Enter Y and press Enter when prompted to continue.

5. Delete the network security group:


Enter Y and press Enter when prompted to continue.

6. Delete the public IP address:

Enter Y and press Enter when prompted to continue.

7. Delete the virtual network:

Enter Y and press Enter when prompted to continue.

8. Delete the managed OS disks:

Enter Y and press Enter when prompted to continue.

9. Verify all resources were removed:

Check the resource group to ensure all resources are removed:


While you executed these commands interactively, a better approach is to write a
PowerShell script. Scripts allow you to reuse the logic for creating or deleting a VM in the
future

Next, let's look at how to automate these tasks using a PowerShell script.
Create Azure Resources with Azure
PowerShell using a script
Complex or repetitive tasks can be time-consuming and error-prone when performed
manually. Organizations prefer to automate these tasks to reduce costs and avoid
mistakes.

Automation is essential in the Customer Relationship Management (CRM) example, where


you're testing your software on multiple Linux virtual machines (VMs) that need to be
continuously deleted and re-created. Using a PowerShell script to automate VM creation is
much more efficient and reliable than manually creating them each time.

Beyond the core operation of creating a VM, your script needs to meet a few other
requirements:

• Create multiple VMs: Use New-AzVM to create multiple uniquely named VMs.

• Resource group parameter: Allow the script to accept the name of the resource
group as a parameter.

In this unit, you learn how to write and execute a PowerShell script that meets these
requirements.

What is a PowerShell script?


A PowerShell script is a text file containing commands and control constructs. The
commands are invocations of cmdlets, and the control constructs are programming
features like loops, variables, parameters, comments, etc. supplied by PowerShell.

PowerShell script files have a .ps1 file extension. You can create and save these files using
any text editor.

The following screenshot is an example of VS Code with a sample script to connect to


Azure and create a virtual machine:
Once you create a script, you can execute it from the PowerShell command line by passing
the name of the file preceded by a dot for the current directory and a backslash:

PowerShell techniques
PowerShell includes features commonly found in programming languages. You can define
variables, use branches and loops, capture command-line parameters, write functions,
add comments, and more. For the script you're focusing on, you need three key features:
variables, loops, and parameters.

Variables
In PowerShell, variables are declared using the dollar sign ($) and assigned values using the
equals (=) operator. For example:

To determine the value stored in a variable, use the $ prefix and its name:
Variables can hold objects. For example, the following definition sets
the $adminCredential variable to the object returned by the Get-Credential cmdlet:

Loops
PowerShell has several loop structures, including For, Foreach, Do-Until, Do-While,
and While. The Foreach loop is a good choice for scenarios where you need to execute a
loop over a set of values in a collection.

Parameters
When you create a PowerShell script, you can add parameters to the script and then
specify values for these parameters when executing the script. For example:

Inside the script, capture the values into variables. In this example, the parameters
are Name and Location:
You can use these parameters as input and a loop to create a set of VMs based on the given
parameters. This approach keeps the script generic and avoids repeating the same code.

Combining techniques
The combination of PowerShell language features and Azure PowerShell cmdlets provides
all the tools you need to automate Azure tasks. In the CRM example, you can create
multiple Linux VMs using a parameterized script and a loop to streamline the process. This
script allows you to perform a complex operation in a single step.

Example script
Here's an example script that demonstrates using variables, loops, and parameters to
create multiple VMs:
Executing the script

Save the script as CreateVMs.ps1 and run it from the PowerShell command line, providing
the required parameters:

PowerShell

Using this script, you can efficiently create multiple VMs in different resource groups,
automating repetitive tasks and ensuring consistency across your Azure environment.

Exercise - Create Azure Resources with


Azure PowerShell using a script
In this unit, you continue with the example of a company that develops Linux admin tools.
The goal is to use Linux virtual machines (VMs) to allow potential customers to test your
software. With a resource group already set up, it's time to create the VMs.

Your company secured a booth at a large Linux trade show. You plan to set up a demo area
with three terminals, each connected to a separate Linux VM. You must delete the VMs and
re-create them at the end of each day so they start fresh every morning. Creating the VMs
manually after a long day is error-prone, so you need to write a PowerShell script to
automate the VM creation process.

Write a script to create virtual machines


Follow these steps to write a script in Azure Cloud Shell that automates the creation of
virtual machines.

1. Switch to your home folder:


2. Create a new PowerShell script file:

3. Open the integrated Visual Studio Code (VS Code) editor:

4. Define a parameter for your resource group name:


Add the following line to your script:

5. Prompt for VM administrator credentials:

6. Create a loop to execute three times:

7. In the loop, return the name for each VM:


8. Create a VM using the $vm variable:

9. Save the file:

To save the script, use the ellipsis (...) context menu at the top-right corner of the editor
or the Ctrl + S keyboard shortcut.

Completed script
The completed script should look like the following example:

Once you confirm your script looks like the code in the previous example, close the editor
using the ellipsis (...) context menu at the top-right corner of the editor, or
the Ctrl + Q keyboard shortcut.
Run the script
1. Execute the script using the following command:

2. Wait for completion. The script takes several minutes to complete.

3. Verify the VMs. Once the script finishes, verify it completed successfully by listing
the VMs in the resource group:

You should see three VMs, each with a unique name.

You successfully created a script that automates the creation of three VMs, each in a
specific resource group, ensuring they're ready for daily demos at the trade show. Although
the script is short and straightforward, it significantly speeds up a process that would
otherwise be time-consuming and error-prone if performed manually through the Azure
portal.

You might also like