PowerShell And Azure CLI Reference

Transcription

PowerShell Reference GuidePowerShell and Azure CLI ReferenceIntroduction:Welcome to the PowerShell Reference Guide. This guide will provide you with a reference tokey PowerShell commands necessary for Azure administrators as well as required to pass theAzure Administrator certification exams from Microsoft.If you are completely new to PowerShell, we highly recommend you check out the MicrosoftAzure PowerShell Overview which has a number of tutorials and guides for learning the basics.This guide is made up of several PowerShell commands which have been reference from theMicrosoft documentation and other sources. Before running any of these commands inproduction, please be sure to test them out in an Azure test account. Some commands aredestructive in nature (e.g. removing resource groups, tags etc.) and you need to make sure youfully understand the commands that you execute.The guide is divided up into the following sections: Downloading PowerShell and Installing Azure ARM Modules for PowerShellAccounts and SubscriptionsResource GroupsGovernanceStorageVirtual MachinesNetworkingAzure Active DirectoryIf you spot any errors in this guide, please submit them via the Contact Us page on the SkylinesAcademy web site.Thank you,Skylines Academy Team 2018 Skylines Academy, LLC All rights reserved

PowerShell Reference GuideDownloading PowerShell:Always make sure you have the latest version of PowerShell ds/All Azure administrators will require PowerShell along with the AzureRM module installed ontheir laptops.Installing AzureRM Module (Windows Example)Installing Azure PowerShell from the PowerShell Gallery requires elevated privileges. Run thefollowing command from an elevated PowerShell session (Search for PowerShell à Right Clickà Run as Administrator)By default, the PowerShell gallery is not configured as a Trusted repository for PowerShellGet.You will see the following prompts. Enter Yes to all. 2018 Skylines Academy, LLC All rights reserved

PowerShell Reference GuideUntrusted repositoryMake sure to choose yes when prompted to install modules from the untrusted repositories.You can make these repos trusted by using the Set-PSRepository cmdlet and changing theinstallation policy if you desire given that the source is PSGallery.Are you sure you want to install the modules from 'PSGallery'?[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"): YAnswer 'Yes' or 'Yes to All' to continue with the installation.NoteIf you have a version older than 2.8.5.201 of NuGet, you are prompted to download and installthe latest version of NuGet. The AzureRM module is a rollup module for the Azure Resource Manager cmdlets. When youinstall the AzureRM module, any Azure PowerShell module not previously installed isdownloaded and from the PowerShell Gallery. If you have a previous version of Azure PowerShell installed you may receive an error. Toresolve this issue, see the Updating to a new version of Azure PowerShell section of thisarticle. Reference: install-azurermps?view re Cloud ShellReference content from following: overview?view azurermps-4.4.0 2018 Skylines Academy, LLC All rights reserved

PowerShell Reference GuideAccounts and SubscriptionsAzure AccountsLogin to Azure AccountLogin-AzureRMAccountLogout of the Azure accountyou are connected with in yoursessionDisconnect-AzureRmAccountNote: Upon entering this command, you will be presented with apopup window to complete your login process and any MFArequirements.Upon entering this command, you will be presented with a popup window to complete your loginprocess and any MFA requirements.Subscription SelectionList all subscriptions in alltenants the account can accessGet-AzureRmSubscriptionGet subscriptions in a specifictenantGet-AzureRmSubscription -TenantId "xxxx-xxxx-xxxxxxxx"Choose subscriptionSelect-AzureRmSubscription –SubscriptionID“SubscriptonID”Note: Use Get-AzureRMSubscription to identity the subscriptionID. 2018 Skylines Academy, LLC All rights reserved

PowerShell Reference GuideResource GroupsRetrieving Resource GroupsFind all resource groupsFind-AzureRmResourceGroup(Searches for them and displaysthem on screen)Get all resource groupsGet-AzureRMResourceGroup(Gets the resource group andadditional details which can alsobe stored for use by additionalcommands)Get a specific resource groupby nameGet-AzureRmResourceGroup -Name "SkylinesRG”Get-AzureRmResourceGroup Where ResourceGroupName Get resource groups wherethe name begins with “Skylines” like Skylines*Show resource groups bylocationGet-AzureRmResourceGroup Sort Location,ResourceGroupName Format-Table -GroupBy sources within RGsFind resources of a type inresource groups with aspecific nameFind-AzureRmResource -ResourceType"microsoft.web/sites" -ResourceGroupNameContains"thistext"Find resources of a typematching against the resourcename stringFind-AzureRmResource -ResourceType"microsoft.web/sites" -ResourceNameContains"thistext"Note: The difference with thiscommand vs the one above, isthat this one does not look fora specific resource group, butrather just all resources with a 2018 Skylines Academy, LLC All rights reserved

PowerShell Reference Guidename containing the textspecified.Resource Group Provisioning & ManagementCreate a new Resource GroupNew-AzureRmResourceGroup -Name 'SkylinesRG' -Location'northcentral'#Creates a new resource group in North Centralcalled “Skylines RG”Delete a Resource GroupRemove-AzureRmResourceGroup -Name "SL-RGToDelete"Moving Resources from one Resource Group to anotherStep 1: Retrieve existingResource Resource Get-AzureRmResource unts" ResourceName "SkylinesStorageAccount"# Retrieves a storage account called “SkylinesStorageAccount”Step 2: Move the Resource tothe New GroupMove-AzureRmResource -ResourceId Resource.ResourceId -DestinationResourceGroupName"SL-NewRG"# Moves the resource from Step 1 into thedestination resource group “SL-NewRG”Resource Group TagsDisplay Tags associated with aspecific resource group name(Get-AzureRmResourceGroup -Name "SkylinesRG").TagsTo get all Azure resourcegroups with a specific tag:(Find-AzureRmResourceGroup -Tag @{Owner "Skylines Academy" }).Name 2018 Skylines Academy, LLC All rights reserved

PowerShell Reference GuideTo get specific resources witha specific tag:(Find-AzureRmResource -TagName Dept -TagValueFinance).NameAdding TagsSet-AzureRmResourceGroup -Name examplegroup -TagAdd Tags to an existingresource group that has no tags @{ Dept "IT"; Environment "Test" }Adding tags to an existingresource group that has tags1. Get Tags2. Append3. Update/Apply Tags tags (Get-AzureRmResourceGroup -Nameexamplegroup).Tags tags @{Status "Approved"}Set-AzureRmResourceGroup -Tag tags -NameexamplegroupAdd tags to a specific resourcewithout tags r Get-AzureRmResource -ResourceNameexamplevnet -ResourceGroupName examplegroupSet-AzureRmResource -Tag @{ Dept "IT";Environment "Test" } -ResourceId r.ResourceId ForceApply all tags from an existingresource group to theresources beneath. (Note: thisoverrides all existing tags onthe resources inside the RG) groups Get-AzureRmResourceGroupforeach ( group in groups){Find-AzureRmResource ResourceGroupNameEquals g.ResourceGroupName ForEach-Object {Set-AzureRmResource -ResourceId .ResourceId -Tag g.Tags -Force }}Apply all tags from a resourcegroup to its resources, butretain tags on resources thatare not duplicates groups Get-AzureRmResourceGroupforeach ( g in groups){if ( g.Tags -ne null) { resources Find-AzureRmResource ResourceGroupNameEquals g.ResourceGroupNameforeach ( r in resources){ resourcetags (Get-AzureRmResource-ResourceId r.ResourceId).Tagsforeach ( key in g.Tags.Keys){if 2018 Skylines Academy, LLC All rights reserved

PowerShell Reference Guide( resourcetags.ContainsKey( key)) { resourcetags.Remove( key) }} resourcetags g.TagsSet-AzureRmResource -Tag resourcetags -ResourceId r.ResourceId -Force}}}Remove all tags (Caution)Removes all tags by passing anempty hashSet-AzureRmResourceGroup -Tag @{} -Nameexampleresourcegroup 2018 Skylines Academy, LLC All rights reserved

PowerShell Reference GuideGovernanceAzure Policies: View Policies and AssignmentsSee all policy definitions in your Get-AzureRmPolicyDefinitionsubscriptionRetrieve assignments for aspecific resource group rg Get-AzureRmResourceGroup -Name"ExampleGroup"(Get-AzureRmPolicyAssignment -NameaccessTierAssignment -Scope rg.ResourceIdCreate PoliciesStep 1Create the policy in JSONStep 2Pass the file usingPowershellExample: definition New-AzureRmPolicyDefinition -Name denyRegions -DisplayName "Deny specific regions" es.json'You can also use a local file as follows: definition New-AzureRmPolicyDefinition -Name denyCoolTiering -Description "Deny cool access tiering forstorage" -Policy "c:\policies\coolAccessTier.json"Assign Policies 2018 Skylines Academy, LLC All rights reserved

PowerShell Reference GuideApply a policy from a definitioncreated above rg Get-AzureRmResourceGroup -Name"ExampleGroup"New-AzureRMPolicyAssignment -Name denyRegions Scope rg.ResourceId -PolicyDefinition definitionResource LocksCreate a new resource lockNew-AzureRmResourceLock -LockLevel ReadOnly LockNotes "Notes about the lock" -LockName "SLWebSiteLock" -ResourceName "SL-WebSite" ResourceType "microsoft.web/sites"# Creates a new ReadOnly resource lock on a web site resource.Retrieve a resource lockGet-AzureRmResourceLock -LockName "SL-WebSiteLock" ResourceName "SL-WebSite" -ResourceType"microsoft.web/sites" -ResourceGroupName "SLRGWebSite" 2018 Skylines Academy, LLC All rights reserved

PowerShell Reference GuideStorageRetrieving Storage AccountsLists all storage accounts in thecurrent subscriptionGet-AzureRMStorageAccountCreate Storage AccountCreate Storage AccountRequires the resource groupname, storage account name,valid Azure location, and type(SkuName).SKU OptionsOptional Key ParametersNew-AzureRmStorageAccount -ResourceGroupName“slstoragerg” -Name “slstorage1” -Location“eastus”-SkuName “Standard LRS” Standard LRS. Locally-redundant storage.Standard ZRS. Zone-redundant storage.Standard GRS. Geo-redundant storage.Standard RAGRS. Read access geo-redundant storage.Premium LRS. Premium locally-redundant storage.-KindThe kind parameter will allow you to specify the type ofStorage Account. Storage - General purpose Storage account thatsupports storage of Blobs, Tables, Queues, Files andDisks.StorageV2 - General Purpose Version 2 (GPv2)Storage account that supports Blobs, Tables, Queues,Files, and Disks, with advanced features like data tiering.BlobStorage -Blob Storage account which supportsstorage of Blobs only. The default value is Storage.-Access Tier 2018 Skylines Academy, LLC All rights reserved

PowerShell Reference GuideIf you specify BlobStorage as the “Kind” then you must alsoinclude an access tier HotColdCreate a storage container in astorage Account (using storageaccount name)New-AzureRmStorageContainer -ResourceGroupName"slstoragerg" -AccountName "slstorageaccount" ContainerName "slContainer"Create a storage containerin a storage account (usingthe storage account object)1. Get the storage account and store it as a variableØ storageaccount Get-AzureRmStorageAccount ResourceGroupName "slstoragerg" -AccountName"slstorageaccount"2. Make sure you have the right oneØ storageaccountThis will show you the storage account object you stored inthe variable storageaccount3. Create the container in the storage account objectØ New-AzureRmStorageContainer -StorageAccount accountObject -ContainerName "slContainer" - 2018 Skylines Academy, LLC All rights reserved

PowerShell Reference GuideRemove Accounts and ContainersDelete a storage accountRemove-AzureRmStorageAccount -ResourceGroupName"slstoragerg" -AccountName "slstorageaccount"Delete a storage containerusing storage account nameand container nameRemove-AzureRmStorageContainer -ResourceGroupName"slstoragerg" -AccountName "slstorageaccount" ContainerName "slcontainer"Delete a storage containerusing the storage accountobjectRemove-AzureRmStorageContainer -StorageAccount storageaccount -ContainerName "slcontainer"Note: Make sure to storage the storage account as avariable first usingØ storageaccount Get-AzureRmStorageAccount ResourceGroupName "slstoragerg" -AccountName"slstorageaccount" 2018 Skylines Academy, LLC All rights reserved

PowerShell Reference GuideDeploy and Manage Virtual MachinesGet Information About VMsTaskCommandList all VMs in currentsubscriptionGet-AzureRmVMList VMs in a resource groupGet-AzureRmVM -ResourceGroupName slResourceGroup(See Resource Groups sectionabove)Get a specific virtual machineGet-AzureRmVM -ResourceGroupName “slresourcegroup” -Name“myVM”Create a VM – SimplifiedI put this command here as it is a quick way to create a VM, but you are far better off using VMconfigurations to create your VMs with more specific parameters applied. Try out both of them and youwill see the difference.TaskCommandCreate aNew-AzureRmVM -Name “vmname”simple VMTyping in this simple command will create a VM and populate names for all the associatedobjects based on the VM name specified. 2018 Skylines Academy, LLC All rights reserved

PowerShell Reference GuideCreate a VM Configuration Before Creating the Virtual MachineUse the following tasks to create a new VM configuration before creating your Virtual Machine based onthat config.TaskCommandCreate a VMconfiguration vmconfig New-AzureRmVMConfig -VMName “systemname” -VMSize"Standard D1 v2"Add configurationsettings vmconfig Set-AzureRmVMOperatingSystem -VM vmconfig -Windows ComputerName “systemname” -Credential

Azure PowerShell Overview which has a number of tutorials and guides for learning the basics. This guide is made up of several PowerShell commands which have been reference from the Microsoft documentation and other sources. Before running any of these commands in production, please be sure to test them out in an Azure test account. Some commands are