{"id":76469,"date":"2017-12-29T16:14:52","date_gmt":"2017-12-29T16:14:52","guid":{"rendered":"https:\/\/www.red-gate.com\/simple-talk\/?p=76469"},"modified":"2021-02-23T19:23:11","modified_gmt":"2021-02-23T19:23:11","slug":"azure-windows-powershell-basics","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/sysadmin\/powershell\/azure-windows-powershell-basics\/","title":{"rendered":"Azure and Windows PowerShell: The Basics"},"content":{"rendered":"<p><strong>The series so far:<\/strong><\/p>\n<ol>\n<li><a href=\"https:\/\/www.red-gate.com\/simple-talk\/sysadmin\/powershell\/azure-windows-powershell-basics\/\">Azure and Windows PowerShell: The Basics<\/a><\/li>\n<li><a href=\"https:\/\/www.red-gate.com\/simple-talk\/sysadmin\/powershell\/azure-and-windows-powershell-getting-information\/\">Azure and Windows PowerShell: Getting Information<\/a><\/li>\n<li><a href=\"https:\/\/www.red-gate.com\/simple-talk\/sysadmin\/powershell\/azure-and-windows-powershell-using-vm-extensions\/\">Azure and Windows PowerShell: Using VM Extensions<\/a><\/li>\n<\/ol>\n\n<p>I often write about Windows PowerShell on Simple-Talk. I write to help readers to automate day-to-day tasks as you can see in my previous series:<\/p>\n<ul>\n<li><a href=\"https:\/\/www.red-gate.com\/simple-talk\/sysadmin\/virtualization\/working-windows-containers-docker-basics\/\">Windows Containers<\/a><\/li>\n<li><a href=\"https:\/\/www.red-gate.com\/simple-talk\/sysadmin\/powershell\/powershell-desired-state-configuration-the-basics\/\">PowerShell DSC<\/a><\/li>\n<li><a href=\"https:\/\/www.red-gate.com\/simple-talk\/sysadmin\/powershell\/automating-day-to-day-powershell-admin-tasks-jobs-and-workflow\/\">PowerShell Day-to-Day Admin Tasks<\/a><\/li>\n<\/ul>\n<p>I believe that almost everything can be done using Windows PowerShell. It is possible to perform just about any task you want assuming you have some scripting skills. That being said, I would like to introduce a new series on Simple-Talk about Azure. I will not explain what Azure is and what it is not, because you can read many great articles on the internet about this topic. Here, I\u2019ll focus on what can be done with Azure and, of course, I will often use Windows PowerShell to describe how to configure and use all the Azure services. Even If you don\u2019t work with Azure, I advise you to give it a try because curiosity is the key for every IT professional. Azure becomes more important and widely used as it grows every day, so understanding the benefits and limits of Azure can help you in your IT career.<\/p>\n<p>Some companies are already working with Azure because they must put their workload into the cloud. Other companies are experimenting with Azure. There are also many companies that can\u2019t jump to the cloud, or simply don\u2019t want to, and may have many good reasons. I hope that this new series will encourage these companies to give a Azure a try. Since I work exclusively with Azure, I can\u2019t compare features between Azure and Amazon AWS, but there are very good comparisons available on the internet. Maybe Azure is not the better choice for your business, so feel free to try Amazon AWS.<\/p>\n<p>Many articles on the internet explain how to deploy or create a Virtual Machine on Azure with Windows PowerShell. This is interesting and useful for beginners but there are so many other services in Azure that must be described.<\/p>\n<p>Another key point about Azure is the ability to automate most tasks. Sometimes, you will not be able to choose between using the Azure Portal or Windows PowerShell because Microsoft doesn\u2019t implement all the action in the Azure Portal. Although conversely, not all tasks can be automated, so it is essential to work with Azure Portal as well. Almost everything can be automated which will save a lot of your time and help you to jump into the cloud!<\/p>\n<p>Please note that you can work with Azure using the following methods:<\/p>\n<ul>\n<li><strong>Azure Portal<\/strong>: The portal allows you to browse resources, modify settings, create new resources, and monitor your resources.<\/li>\n<li><strong>Azure Windows PowerShell<\/strong>: The Azure PowerShell Module will help you to manage your Azure resources. You can use it on your local machine or in your web browser.<\/li>\n<li><strong>Azure CLI<\/strong>: Azure CLI (command line interface) is the next generation multi-platform command line experience for managing Azure resources. You can use it on MacOS, Linux and Windows. You also can use it in a web browser.<\/li>\n<li><strong>Azure REST API<\/strong>: Representational State Transfer (REST) APIs are service endpoints that support sets of HTTP operations (methods), which provide create, retrieve, update, or delete access to the service&#8217;s resources. Note that I will not cover this method in this series.<\/li>\n<\/ul>\n<p>As you can see, Windows PowerShell is not the only method available to work with Azure. In this series, I will also provide Azure CLI commands when it\u2019s possible. Azure CLI is simpler than PowerShell but the main advantage of PowerShell is the community. You will notice that there are many PowerShell script examples available for Azure.<\/p>\n<p>Before going deeper into Azure services, this first article will cover the basics by describing how to login to Azure and how to configure your scripting environment. I hope you will find this series interesting and helpful.<\/p>\n<h2>Using the Azure Cloud Shell<\/h2>\n<p>Azure Cloud Shell is one method to manage your Azure resources that are available without installing anything on your local system. It provides secure terminal access to a virtual machine without the need to install and maintain the machine yourself. In fact, the virtual machine is created and deleted as needed. Azure Cloud Shell can be accessed within a web browser through the Azure Portal, and you can use it with both PowerShell and Azure CLI commands. With Azure Cloud Shell, you always have the most up-to-date version of the tools available and you don\u2019t have to install or update it.\u00a0Azure Cloud Shell requires an Azure File Share to persist files, so Azure will create a new storage account for you and this will incur a small monthly cost. First, login to the Azure Portal <a href=\"https:\/\/portal.azure.com\">https:\/\/portal.azure.com<\/a> as shown in Figure 1 and click on the Cloud Shell icon.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"716\" height=\"67\" class=\"wp-image-76471\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2017\/12\/word-image-53.png\" \/><\/p>\n<p class=\"caption\">Figure 1 \u2013 Azure Cloud Shell icon<\/p>\n<p>Wait a few seconds and a PowerShell console will appear. It will take a minute or to authenticate as shown in Figure 2, but authentication is automatic<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"691\" height=\"324\" class=\"wp-image-76472\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2017\/12\/word-image-54.png\" \/><\/p>\n<p class=\"caption\">Figure 2 \u2013 Azure Cloud Shell using Windows PowerShell<\/p>\n<p>Note that you can select PowerShell or Bash from the shell drop-down list to manage your Azure resources. Figure 3 shows the Bash option. Azure Cloud Shell gives you the flexibility of choosing the shell experience that best suits the way you work. If you are a Linux user, then you can opt for a Bash experience, while Windows users can opt for Windows PowerShell. Remember that Azure Cloud Shell is designed to be a flexible and cross-platform tool.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"546\" height=\"250\" class=\"wp-image-76474\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2017\/12\/word-image-55.png\" \/><\/p>\n<p class=\"caption\">Figure 3 \u2013 Azure Cloud Shell using Bash<\/p>\n<p>In my case, I will always use the PowerShell console instead of the Bash console. From this console you can use the Azure PowerShell Module or Azure CLI. Run the following PowerShell command to get the subscription ID, subscription name, and home tenant for the subscriptions that the current account can access.<\/p>\n<pre class=\"theme:powershell-output lang: ps decode:true\">Azure:\\\r\nPS Azure:\\&gt; Get-AzureRmSubscription\r\n\r\n\r\nName     : Visual Studio Enterprise\r\nId       : xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\r\nTenantId : yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy\r\nState    : Enabled\r\n<\/pre>\n<p>You can also use Azure CLI to get the same information by running the following command:<\/p>\n<pre class=\"theme:powershell-output lang: ps decode:true\">Azure:\\\r\nPS Azure:\\&gt; az account list --output table\r\n\r\nName                      CloudName    SubscriptionId                        State   IsDefault\r\n------------------------  -----------  ------------------------------------  ------- ---------\r\nVisual Studio Enterprise  AzureCloud   xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx  Enabled True\r\n<\/pre>\n<h2>Configuring the Local Scripting Environment<\/h2>\n<p>The other option, and possibly the most common, is using the local computer to write and run scripts. Let\u2019s start by installing Azure CLI. You can install Azure CLI on MacOS, Linux, and Windows.<\/p>\n<p>To run Azure CLI on your workstation, you must download the MSI from: <a href=\"https:\/\/aka.ms\/InstallAzureCliWindows\">https:\/\/aka.ms\/InstallAzureCliWindows<\/a>. Once the installation is completed, open a PowerShell console and type the following command to confirm that Azure CLI is available:<\/p>\n<pre class=\"theme:powershell-output lang: ps decode:true\">Windows PowerShell\r\nCopyright (C) 2016 Microsoft Corporation. All rights reserved.\r\n\r\nPS C:\\Users\\Nicolas&gt; az\r\n\r\n     \/\\\r\n    \/  \\    _____   _ _ __ ___\r\n   \/ \/\\ \\  |_  \/ | | | \\'__\/ _ \\\r\n  \/ ____ \\  \/ \/| |_| | | |  __\/\r\n \/_\/    \\_\\\/___|\\__,_|_|  \\___|\r\n\r\n\r\nWelcome to the cool new Azure CLI!\r\n\r\nHere are the base commands:\r\n\r\n    account          : Manage subscriptions.\r\n    acr              : Manage Azure Container Registries.\r\n    acs              : Manage Azure Container Services.\r\n    ad               : Synchronize on-premises directories and manage Azure Active Directory\r\n                       resources.\r\n    appservice       : Manage your App Service plans.\r\n    batch            : Manage Azure Batch.\r\n    billing          : Manage Azure Billing.\r\n    cdn              : Manage Azure Content Delivery Networks (CDN).\r\n    cloud            : Manage the registered Azure clouds.\r\n    cognitiveservices: Manage Cognitive Services accounts in Azure Resource Manager.\r\n    component        : Manage and update Azure CLI 2.0 components.\r\n    configure        : Configure Azure CLI 2.0 or view your configuration. The command is\r\n                       interactive, so just type `az configure` and respond to the prompts.\r\n    consumption      : Manage Azure Consumption.\r\n    container        : (Preview) Manage Azure Container Instances.\r\n[\u2026]\r\nNote that output has been truncated.\r\n<\/pre>\n<p>One thing to notice is the Azure CLI version. Run the following command to check the installed version:<\/p>\n<pre class=\"theme:powershell-output lang: ps decode:true\">PS C:\\Users\\Nicolas&gt; az --version\r\nazure-cli (2.0.16)\r\n<\/pre>\n<p>There are two main versions of Azure CLI in use. If you are using the classic Azure Service Manager (ASM) deployments, you will need Azure CLI 1.0. In version 1.0, the commands start with <strong>azure<\/strong>. If you use, instead, the newer and preferred Azure Resource Manager (ARM) deployments, you will use Azure CLI 2.0, and the commands begin with <strong>az<\/strong>. If you want to know more about the key difference between ASM and ARM, please <a href=\"https:\/\/docs.microsoft.com\/en-us\/azure\/azure-resource-manager\/resource-manager-deployment-model\">read this guide<\/a>.<\/p>\n<p>Now let\u2019s install the Azure PowerShell module. I think using the PowerShell Gallery is the easiest and fastest way to install it. Open your PowerShell console as an administrator and use the following PowerShell command :<\/p>\n<pre class=\"theme:powershell-output lang: ps decode:true\">  PS &gt; Install-Module AzureRM\r\n<\/pre>\n<p>Let\u2019s confirm if the module is installed:<\/p>\n<pre class=\"theme:powershell-output lang: ps decode:true\">PS C:\\WINDOWS\\system32&gt; Get-Module -ListAvailable *Azure*\r\n\r\n\r\n    Directory: C:\\Program Files\\WindowsPowerShell\\Modules\r\n\r\n\r\nModuleType Version    Name                              ExportedCommands\r\n---------- -------    ----                              ----------------\r\nScript     0.5.0      Azure.AnalysisServices            {Add-AzureAnalysisServicesAccount,..\r\nScript     0.4.2      Azure.AnalysisServices            {Add-AzureAnalysisServicesAccount,..\r\nScript     4.0.2      Azure.Storage                     {Get-AzureStorageTable, New-..\r\nScript     3.2.1      Azure.Storage                     {Get-AzureStorageTable, New-..\r\nScript     0.6.0      AzurePSDrive\r\nScript     5.1.1      AzureRM\r\nScript     4.2.1      AzureRM                           {New-AzureRmAnalysisServicesServer,..\r\n[\u2026]\r\nNote that output has been truncated.\r\n<\/pre>\n<p>Remember to update the Azure PowerShell module on a regular basis using the <strong>Update-Module<\/strong> cmdlet.<\/p>\n<h2>Login to Azure<\/h2>\n<p>You can now begin scripting your Azure tasks! The first thing to do is to be able to login on Azure. The easiest way to perform this task is to use the <strong>Login-AzureRMLogin <\/strong>cmdlet. With no other parameters provided, this will pop up a login box where you can enter your Azure credentials. Then, it will create an authentication context for your PowerShell Session:<\/p>\n<pre class=\"theme:powershell-output lang: ps decode:true\">PS C:\\WINDOWS\\system32&gt; Login-AzureRmAccount\r\n\r\n\r\nEnvironment           : AzureCloud\r\nAccount               : mail@domain.com\r\nTenantId              : yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy\r\nSubscriptionId        : xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx \r\nSubscriptionName      : Visual Studio Enterprise\r\nCurrentStorageAccount :\r\n<\/pre>\n<p>If you are using it against the classic Azure Portal you can use the <strong>Install-Module Azure<\/strong> command and then use the following command to login: <strong>Add-AzureAccount<\/strong>.<\/p>\n<p>To view some details about your session, run the <strong>Get-AzureRmContext<\/strong> cmdlet.<\/p>\n<h2>Automating Azure Login with PowerShell<\/h2>\n<p>After few days of working with Azure, you will notice that the login step is boring. Fortunately, you can automate this step by saving your Azure RM context in a JSON file. The <strong>Save-AzureRmContext<\/strong> cmdlet saves the current authentication information for use in other PowerShell sessions. Running this cmdlet has security implications for your Azure environment, so you need to be sure that your context file is stored in a safe location.<\/p>\n<p>First you must run the <strong>Login-AzureRmAccount<\/strong> cmdlet and next, run the following command:<\/p>\n<pre class=\"theme:powershell-output lang: ps decode:true\">  PS &gt; Save-AzureRmContext -Path \"C:\\AzureProfile.json\"\r\n<\/pre>\n<p>Thanks to this JSON file, you can now login to Azure very quickly. I will first check that I am not logged in to my Azure subscription:<\/p>\n<pre class=\"theme:powershell-output lang: ps decode:true\">PS C:\\Users\\Nicolas&gt; Get-AzureRmVM\r\nGet-AzureRmVM: Run Login-AzureRmAccount to login.\r\nAt line:1 char:1\r\n+ get-azurermvm\r\n+ ~~~~~~~~~~~~~\r\n    + CategoryInfo          : InvalidOperation: (:) [Get-AzureRmVM], PSInvalidOperationException\r\n    + FullyQualifiedErrorId : InvalidOperation,Microsoft.Azure.Commands.Compute.GetAzureVMCommand\r\n<\/pre>\n<p>The error message shows that I&#8217;m not logged in.\u00a0 Now I can use my JSON file using the <strong>Import-AzureRmContext<\/strong> cmdlet:<\/p>\n<pre class=\"theme:powershell-output lang: ps decode:true\">PS C:\\Users\\Nicolas&gt; Import-AzureRmContext -Path \"C:\\AzureProfile.json\"\r\n\r\n\r\nEnvironment           : AzureCloud\r\nAccount               : mail@domain.com \r\nTenantId              : yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy\r\nSubscriptionId        : xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx \r\nSubscriptionName      : Visual Studio Enterprise\r\nCurrentStorageAccount :\r\n<\/pre>\n<p>Done! Now, I can list my Azure Virtual Machines available in my subscription:<\/p>\n<pre class=\"theme:powershell-output lang: ps decode:true\">PS C:\\Users\\Nicolas&gt; Get-AzureRmVM\r\n\r\nResourceGroupName         Name   Location           VmSize  OsType  ProvisioningState\r\n-----------------         ----   --------           ------  ------  -----------------\r\nNICO-RG01           Win10-1709   westeurope Standard_D2_v2  Windows Succeeded\r\nNICO-RG02         Win2016-1709   westeurope Standard_D1_v2  Windows Succeeded\r\n<\/pre>\n<p>The <strong>Login-AzureRmAccount<\/strong> cmdlet is an Alias for <strong>Add-AzureRmAccount<\/strong> cmdlet, so they both do the same thing. The <strong>Add-AzureAccount<\/strong> cmdlet is the old service management (classic) command for accessing Azure, which you would use if you needed to access classic resources. The <strong>Login-AzureRmAccount<\/strong> cmdlet is used for access to the new ARM services.<\/p>\n<p>Here is another important point to notice. If you try to run the following command it will bring up a Windows login dialog in which you must enter your Azure credentials:<\/p>\n<pre class=\"theme:powershell-output lang: ps decode:true\">PS &gt; $cred = Get-Credential\r\nPS &gt; Login-AzureRmAccount \u2013Credential $cred\r\n<\/pre>\n<p>You may get the following error:<\/p>\n<pre class=\"theme:powershell-output lang: ps decode:true\">Login-AzureRmAccount : Sequence contains no elements\r\nAt line:4 char:1\r\n+ Login-AzureRmAccount -Credential $cred\r\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n+ CategoryInfo : CloseError: (:) [Add-AzureRmAccount], AadAuthenticationFailedException\r\n+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.AddAzureRMAccountCommand\r\n<\/pre>\n<p>If you get this error, it means that you probably used your Hotmail or Live account. Unfortunately, this is a platform limitation because Microsoft accounts cannot be used in the non-interactive flow. You must use a work\/school account, but if you don\u2019t have one, the advice for automating you login is to use your JSON file to automate the login processor or to create an Azure RM service principal using the <strong>New-AzureRmADServicePrincipal<\/strong> cmdlet. I will cover this point in the next article.<\/p>\n<h2>Conclusion<\/h2>\n<p>This first article in this series described very basic tasks such as:<\/p>\n<ul>\n<li>Login on Azure<\/li>\n<li>Automating the login process<\/li>\n<li>Installing the Azure PowerShell Module.<\/li>\n<\/ul>\n<p>The basics are important in order to start working with Azure, and that is the reason why I selected this topic to begin this new series. For those of you who are wondering which method they must use to manage Azure resources, well that\u2019s a good question because &#8220;it depends&#8221;. It depends on your preferences and your scripting skills. I would advise you to use the Azure PowerShell Module because, in my point of view, it\u2019s easier to work with Azure and PowerShell. If you usually work with PowerShell in your job, you will save time. On top of that, as PowerShell is the Microsoft Shell created to manage Microsoft products, I think it is reasonable to use it with Azure as well. Of course, you have many good choices, so feel free to use your preferred method.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>IT shops do not want to spend time and energy managing infrastructure and servers as was done in the past. They must conserve resources for the things that add value for the business. Today, it is challenging for companies to automate and configure their Azure infrastructure. In the first part of his new series, Nicolas Prigent introduces the basics about Azure and Windows PowerShell for DevOps and Sysadmin.&hellip;<\/p>\n","protected":false},"author":158223,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[137091,35],"tags":[95506],"coauthors":[6804],"class_list":["post-76469","post","type-post","status-publish","format-standard","hentry","category-azure","category-powershell","tag-automate"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/76469","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/158223"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=76469"}],"version-history":[{"count":9,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/76469\/revisions"}],"predecessor-version":[{"id":76478,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/76469\/revisions\/76478"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=76469"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=76469"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=76469"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=76469"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}