POWERSHELL REFERENCE GUIDE - Microsoft

Transcription

POWERSHELLREFERENCE GUIDESkylines AcademyAzure Study Group@SkylinesAcademywww.skylinesacademy.com

PowerShell Reference GuidePOWERSHELL REFERENCE GUIDEIntroduction: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.This guide uses the recently released Azure “Az” module which is currently in version 1.0.0.This module is intended to be more robust as it is built on .NET Standard. Microsoft currentlyplans to focus on building out and supporting the “Az” Module as the primary PowerShellmodule for interacting with Azure, a shift from the previous “AzureRM” Module. Informationfor supporting existing PowerShell scripts using the “AzureRM” modules is discussed below.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 followingsections: Downloading PowerShell and Installing Azure AZ 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 TeamDownloading PowerShell:Always make sure you have the latest version of PowerShell installed https://azure.microsoft.com/engb/downloads/ 2019 Skylines Academy, LLC All rights reserved

PowerShell Reference GuideAll Azure administrators will require PowerShell along with the Az module installed on theirlaptops.Install AZ Module for Existing AzureRM ModuleIf you already have AzureRM Modules installed on your computer, you’ll want to uninstall theexisting AzureRM Modules before installing the new AZ Modules, as the modules cannotfunction side-by-side. You will have the option of enabling the AzureRM alias to continue usingthe syntax you’re comfortable with and ensure that existing PowerShell scripts continue tofunction properly.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. 2019 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: installazurermps?view re Cloud ShellReference content from following: verview?view azurermps-4.4.0 2019 Skylines Academy, LLC All rights reserved

PowerShell Reference GuideAccounts and SubscriptionsAzure AccountsLogin to Azure AccountLogin-AzAccountNote: Upon entering this command, you will be redirected tohttps://microsoft.com/devicelogin and presented with a popupwindow to complete your login process and any MFA requirements.Logout of the Azure accountyou are connected with in yoursessionLogout-AzAccountUpon 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-AzSubscriptionGet subscriptions in a specifictenantGet-AzSubscription -TenantId "xxxx-xxxx-xxxxxxxx"Choose subscriptionSelect-AzSubscription –SubscriptionID“SubscriptonID”Note: Use Get-AzSubscription to identity the subscriptionID. 2019 Skylines Academy, LLC All rights reserved

PowerShell Reference GuideResource GroupsRetrieving Resource GroupsGet all resource groupsGet-AzResourceGroup(Gets the resource group andadditional details which can alsobe stored for use by additionalcommands)Get a specific resource groupby nameGet-AzResourceGroup -Name "SkylinesRG”Get resource groups where the Get-AzResourceGroup Where ResourceGroupName -likeSkylines*name begins with “Skylines”Show resource groups bylocationGet-AzResourceGroup Sort Location,ResourceGroupName Format-Table -GroupBy sources within RGsFind resources of a type inresource groups with aspecific nameGet-AzResource -ResourceGroupName "SkylinesRG"Find resources of a typematching against the resourcename stringGet-AzResource -ResourceType"microsoft.web/sites" -ResourceGroupName"SkylinesRG"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 2019 Skylines Academy, LLC All rights reserved

PowerShell Reference Guidename containing the textspecified.Resource Group Provisioning & ManagementCreate a new Resource GroupNew-AzResourceGroup -Name 'SkylinesRG' -Location'northcentral'#Creates a new resource group in NorthCentralcalled “Skylines RG”Delete a Resource GroupRemove-AzResourceGroup -Name "SL-RGToDelete"Moving Resources from One Resource Group to AnotherStep 1: Retrieve existingResource Resource Get-AzResource unts" ResourceName "SkylinesStorageAccount"# Retrieves a storage account called“SkylinesStorageAccount”Step 2: Move the Resource tothe New GroupMove-AzResource -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-AzResourceGroup -Name "SkylinesRG").TagsTo get all Azure resourcegroups with a specific tag:(Get-AzResourceGroup -Tag @{Owner "Skylines Academy"}).Name 2019 Skylines Academy, LLC All rights reserved

PowerShell Reference GuideTo get specific resources with(Get-AzResource -TagName Dept -TagValuea specific tag:Finance).NameAdding TagsSet-AzResourceGroup -Name examplegroup -Tag @{Add 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-AzResourceGroup -Nameexamplegroup).Tags tags @{Status "Approved"}Set-AzResourceGroup -Tag tags -Name examplegroupAdd tags to a specific resourcewithout tags r Get-AzResource -ResourceName examplevnet ResourceGroupName examplegroupSet-AzResource -Tag @{ Dept "IT";Environment "Test" } -ResourceId r.ResourceId ForceApply all tags from an existingresource group to theresources beneath. (Note: thisoverrides all existing tags on theresources inside the RG) groups Get-AzResourceGroupforeach( group in groups){Find-AzResource ResourceGroupNameEquals g.ResourceGroupName ForEach-Object {Set-AzResource -ResourceId .ResourceId -Tag g.Tags -Force } } 2019 Skylines Academy, LLC All rights reserved

PowerShell Reference GuideApply all tags from a resourcegroup to its resources, butretain tags on resources thatare not duplicates groups Get-AzResourceGroup foreach ( gin groups){if ( g.Tags -ne null) { resources Find-AzResourceResourceGroupNameEquals g.ResourceGroupNameforeach ( r in resources){ resourcetags (Get-AzResource-ResourceId r.ResourceId).Tagsforeach ( key in g.Tags.Keys){if( resourcetags.ContainsKey( key)) { resourcetags.Remove( key) }} resourcetags g.TagsSet-AzResource -Tag resourcetags -ResourceId r.ResourceId -Force}}}Remove all tags (Caution)Removes all tags by passing anempty hashSet-AzResourceGroup -Tag @{} -Nameexampleresourcegroup 2019 Skylines Academy, LLC All rights reserved

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

PowerShell Reference GuideAssign PoliciesApply a policy from a definitioncreated above rg Get-AzResourceGroup -Name"ExampleGroup"New-AzPolicyAssignment -Name denyRegions Scope rg.ResourceId -PolicyDefinition definitionResource LocksCreate a new resource lockNew-AzResourceLock -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-AzResourceLock -LockName "SL-WebSiteLock" ResourceName "SL-WebSite" -ResourceType"microsoft.web/sites" -ResourceGroupName "SLRGWebSite" 2019 Skylines Academy, LLC All rights reserved

PowerShell Reference GuideStorageRetrieving Storage AccountsLists all storage accounts in thecurrent subscriptionGet-AzStorageAccountCreate Storage AccountCreate Storage AccountRequires the resource groupname, storage account name,valid Azure location, and type(SkuName).SKU OptionsOptional Key ParametersNew-AzStorageAccount -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 2019 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-AzStorageContainer -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-AzStorageAccount 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 NewAzStorageContainer -StorageAccount accountObject -ContainerName "slContainer" - 2019 Skylines Academy, LLC All rights reserved

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

PowerShell Reference GuideDeploy and Manage Virtual MachinesGet Information About VMsTaskCommandGet-AzVMList all VMs in current subscriptionGet-AzVM -ResourceGroupName slResourceGroupList VMs in a resource group(See Resource Groups sectionabove)Get a specific virtual machineGet-AzVM -ResourceGroupName “slresourcegroup” -Name“myVM” 2019 Skylines Academy, LLC All rights reserved

PowerShell Reference GuideCreate 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 differenc

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