Azure PowerShell and CLI

  • Install PowerShell on Ubuntu 16:
  • Powershell Basic cmdlets:
    • pwsh                                                  (Start the PowerShell console)
    • verb-noun -param Arg1, Arg2  (General syntax)
    • Alias:
      • Get-Alias | gal
      • Get-Alias -Definition Get-Process   (Get alias for Get-Process cmdlet)
      • gal ls
      • gal sa*                                                  (List alias starting with sa)
      • pwd: Get-Location
      • cls: Clear-Host
      • dir: Get-ChildItem
      • ps: Get-Process
      • copy: Copy-Item
    • Get-Help:
      • Update-Help -force
      • help  g*process                                    (Get-Help)
      • Get-Help  Get-Process  [-Detailed | -full | -Online | -ShowWindow ]
      • Get-Verb | measure
      • Get-Noun | measure
    • Command:
      • Get-Command -Noun process
      • Get-Command -Verb new
      • Get-Command                        (List all available commands)
      • Get-Command Get-Windows*
    •  Module:
      • Import-Module ServerManager
      • Get-WindowsFeature
      • Add-WindowsFeature Web-Server, telnet-client
      • foreach  {Get-Command  -Module $_}
      • Get-Module -List-Available -Name Azure*
      • Get-InstalledModule -Name AzureRm
      • (Get-Module AzureRm).version
      • Install psm1 module files:
        • Create a folder same as module name in as:
          C:\Users\users1\Documents\WindowsPowerShell\Modules\MyMod1\MyMod1.psm1
    • Process | Service | WmiObject:
      • Get-Process | Sort-Object cpu [pm|handles, ProcessName]
      • Get-Process | Where-Object -EQ ProcessName notepad | Stop-Process
      • Get-Process | Where {$_.handles -gt 1000} | sort handles
        • Get-Process | Where handles -gt 1000 | sort handles
      • Get-Process -Name notepad|Out-File -FilePath process.txt (cat process.txt)
      • Get-Service | Select name,status
      • Get-Service | Where {$_.status -eq “Running” -and $PSItem.name -like “b*”}
      • Get-Service | select @{n=’Services’;e={$_.name}}, Status
      • Get-Service > d:\services.txt
      • Get-Service -Out-Gridview
      • Get-Service | Export-Csv -Path c:\services.csv
      • Get-Process | Export-Clixml -Path c:\services.csv
      • Get-Service | ConvertTo-html -Property name,status | out-file c:\srv.html
      • Get-Service -DisplayName “*bi*” | Stop-Service -whatif | -confirm
      • Get-AdComputer -filter * | Get-WmiObject win32_bios -ComputerName {$_.name}
    • Remoting:
      • Enable-PSRemoting
      • $s = Enter-PSSession  mypc  (mstsc /v:mypc)
      • $s = New-PSSession -ComputerName host1
        • Import-Session -Module ActiveDirectory -Prefix remote
      • Invoke-Command  -ComputerName host1,localhost [-Session $s]
        {Get-EventLog -LogName Security -Newest 10} | Sort TimeWritten |
        Format-Table -Property TimeWritten,Message
      • icm host1,host2 {get-volume} | sort sizeremaining | Select last 3
      • Measure-Command {icm -comp host1 {Get-Process}}
      • $hosts = host1, host2
        • $hosts | foreach {copy-item c:\default.htm -destination \\$_\c$\inetpub\wwwroot}
      • Install-WindowsFeature WindowsPowerShellWebAccess
      • Install-PswaWebApplication -UseTestCertificate
      • Add-PswaAuthorizationRule  * * *
      • start iexplorer https://mypc/pwsa
      • Test-NetConnection -ComputerName <IP> -TraceRoute
    • Set-Location (sl) /tmp
    • Get-WindowsFeature where installed -eq $true
    • Get-WindowsFeature web-server | Install-WindowsFeature
    • Enable-WindowsOptionalFeature
    • Install-WindowsFeature -Name Web-Server  -IncludeManagementTools `
      -ComputerName vm1 -Credential admin\password
    • Get-Volume
    • Get-WmiObject win32_logicaldisk -Filter “DeviceID=’c:'” | select @{n=’freegb’;e={$_.freespace / 1gb -as [int]}}
    • $PSVersionTable                    (Show version)
    • $env:PSModulePath -split “;”
  • PowerShell Azure cmdlets:
    • Install Azure PowerShell on Windows:
      • Run Windows PowerShell ‘Run as administrator’
      • Install-Module AzureRm
      • Update-Module AzureRm
      • Get-Module -ListAvailable AzureRM | (Get-Module AzureRm).version
      • Get-Command *rmstorage*
      • Get-Help New-AzureStorageAccount -full
      • Unblock-File -Path D:\script1.ps1      (Unblock and run scrip1)
        • D:\script.ps1
      • Note: running scripts on your computer has been disabled:
        • Set-ExecutionPolicy Unrestricted [RemoteSigned]
        • Import-Module AzureRM
        • Set-ExecutionPolicy Restricted
    • Basic cmdlets:
      • Get-AzureRmLocation
      • Get-AzureRmVMSize -Location “East US”
      • Get-AzureRmVM  -ResourceGroupName “rg1
      • Get-AzureRmStorageAccount -ResourceGroupName “rg1
    • Login
      • Login-AzureRmAccount | Logout-AzureRmAccount
      • Set-AzureRmContext -SubscriptionId <ID>  (If multiple subscriptions)
      • Select-AzureRmSubscription -SubscriptionId <SubscriptionID>
      • Get-AzureRmSubscription | sort SubscriptionName | Select SubscriptionName
    • RBAC:
      • Get-AzureRmRoleDefinition | Select-Object Name  (List built-in roles)
      • (Get-AzureRmRoleDefinition -Name Reader).Actions
      • Get-AzureRmProviderOperation Microsoft.Compute/*/action | `
        Select-Object Operation, OperationName
      • New-AzureRmRoleAssignment -ObjectId $adGroups[0].Id.Guid `
        -RoleDefinitionName ‘Role1’ -Scope “/subscriptions/$subscriptionID”
    • Users and Groups module:
      • AzureRmAd:
        • Get-AzureRmAdUser -StartsWith “User1”
        • Get-AzureRmAdGroup -DisplayNameStartsWith “Group1”
      • AD DS:
        • New-ADOrganizationalUnit -Name Org1 -Path “DC=adatum,DC=com” -ProtectedFromAccidentalDeletion $false
        • New-ADUser -Name ‘User1’ -GivenName ‘User1’ -Surname ‘Last1’ -SamAccountName ‘user1’ -UserPrincipalName ‘user1@adatum.com’ -AccountPassword (ConvertTo-SecureString -AsPlainText ‘Passw0rd’ -Force) -Path “OU=Org1,DC=adatum,DC=com” -PassThru | Enable-ADAccount
        • Get-ADUser -Filter * | Select DistinguishedName
        • $user = Get-ADUser -Filter “SamAccountName -eq ‘user1‘” -Properties Department,Title -SearchBase ‘OU=Org1,DC=adatum,DC=com’
        • $user | Set-ADUser -Title ‘VP’ -Department ‘Marketing’
        • $user | Get-ADUser -Properties Department,Title
        • Synchronize AD DS and Azure AD:
          • Import-Module “C:\Program Files\Microsoft AZure AD Sync\Bin\ADSync\ADSync.psd1”
          • Get-ADSyncScheduler
          • Start-ADSyncSyncCycle -PolicyType Delta
      • MSOnline:
        • Install-Module MSOnline
        • Connect-MsolService
        • New-MsolUser -UserPrincipalName user1@dir.onmicrosoft.com -DisplayName ‘User1’ -FirstName ‘User1’ -LastName ‘Dir1’ -Password ‘Passw0rd’ -ForceChangePassword $false -UsageLocation ‘US’
        • $user = Get-MsolUser | Where DisplayName -eq ‘User1’
        • New-MsolGroup -DisplayName ‘Group1’ -Description ‘a group’
        • $group = Get-MsolGroup | Where DisplayName -eq ‘Group1’
        • Add-MsolGroupMember -GroupObjectId $group.ObjectId -GroupMemberType ‘User’ -GroupMemberObjectId $user.ObjectId
        • Get-MsolGroupMember -GroupObjectId $group.ObjectId
        • Get-MsolDirSyncConfiguration
        • Set-MsolDirSyncEnabled -EnableDirSync $false
    • Policies:
      • New-AzureRmPolicyDefinition -Name policy1 -Policy C:\policy1.json
      • Get-AzureRmPolicyDefinition -Name policy1
      • New-AzureRmPolicyAssignment -Name pa1 -PolicyDefinition policy1
        -Scope $rg1.ResourceId -Verbose
      • Get-AzureRmPolicyAssignment -Name pa1 -PolicyDefinition policy1
        -Scope $rg1.ResourceId -Verbose
    • Resources:
      • Get-AzureRmResource | Where ResourceType -like “*virtualMachines*”
      • Get-AzureRmResource | Where {$_.Name -like “*vm3*” -or $_.Name -like “*vm4*”} | select Name, ResourceType | sort Name
      • Get-AzureRmResource | Where {$_.Name -like “vm-*” -and $_.ResourceType -eq ‘Microsoft.Compute/virtualMachines‘}
    • Resource Groups:
      • New-AzureRmResourceGroup  -Name ‘rg1‘ -Location ‘East US
      • Get-AzureRmResourceGroup [-Name rg1]
      • Remove-AzureRmResourceGroup -Name ‘rg1
      • Set-AzureRmResourceGroup -Name rg1
        -Tag @{Dept=”IT”; Owner=”User1″}
    • Resource Providers:
      • Get-AzureRmResourceProvider |
        Select  ProviderNamespace, ResourceTypes | Sort ProviderNamespace
      • Get-AzureRmResourceProvider -ProviderNamespace Microsoft.Compute
        -Location ‘East US’ | select ProviderNamespace, ResourceTypes
      • Get-AzureRmResource | Select Name, ResourceType
    • WebApps:
      • New-AzureRmAppServicePlan -ResourceGroupName rg1 -Location centralindia -Name plan1 -Tier Free
      • New-AzureRmWebApp -ResourceGroupName rg1 -Location centralindia -AppServicePlan plan1 -Name webapp1
      • New-AzureRmWebAppSlot -ResourceGroupName rg1 -AppServicePlan plan1 -Name webapp1 -Slot Staging
      • Swap-AzureRmWebAppSlot -ResourceGroupName rg1 -Name webapp1 -SourceSlotName Staging -DestinationSlotName production
    • Basic Azure Cmdlets:
      • Get-AzureRmVM  [-ResourceGroupName rg1  -VMName vm1]
        • (Get-AzureRmVM vm1).StorageProfile.OsDisk
      • Get-AzureRmVMSize -ResourceGroupName rg1  -VMName vm1
      • Update-AzureRmVM -ResourceGroupName rg1  -VM $vm
      • Stop-AzureRmVM -ResourceGroupName rg1  -Name vm1
      • Start-AzureRmVM -ResourceGroupName rg1  -Name vm1
      • Enter-PSSession -ComputerName <Public-IP> -Credential (Get-Credential) -UseSSL -SessionOption (New-PSSsessionOption -SkipCACheck -SkipCNCheck)
      • ConvertTo-AzureRmManagedDisk -ResourceGroupName rg1  -VMName vm1
      • Add-AzureRmVhd -ResourceGroupName disks -Desitination “https://vmstorecjh.blob.core.windows.net/vhd/mydata.vhd&#8221; -LocalFilePath D:\mydata.vhd -Verbose
      • $publicIP = New-AzureRmPublicIpAddress -Name pubIp -ResourceGroupName rg1 -Location “east us” –AllocationMethod Static -DomainNameLabel loadbalancernrp
      • New-AzureRmVirtualNetwork
      • New-AzureRmResourceGroupDeployment -Name $depName `
        ResourceGroupName $rg1.ResourceGroupName `
        -TemplateFile template.json   -TemplateParameterFile params.json `
        @additionalParameters -Verbose -Force
      • Get VM Images and Sizes:
        • Get-AzureRmVMSize -Location “East US”
        • Get-AzureRmVmImagePublisher -Location “East US”
        • Get-AzureRmVmImageOffer -Location “East US” -PublisherName “MicrosoftWindowsServer”
        • Get-AzureRmVmImageSku -Location “East US” -PublisherName “MicrosoftWindowsServer” -Offer “WindowsServer”
        • Get-AzureRmVmImage -Location “East US” -PublisherName “MicrosoftWindowsServer” -Offer “WindowsServer” -Skus “2016-Datacenter-Server-Core”
        • $AzureImageSku = Get-AzureRmVmImage -Location “East US” -PublisherName “MicrosoftWindowsServer” -Offer “WindowsServer” -Skus “2016-Datacenter-Server-Core” | `
          Sort-Object Version -Descending
        • $latestImage = $AzureImageSku[0]
      • Azure DNS:
        • PS> $zone = Get-AzureRmDnsZone -Name abc.com -ResourceGroupName rg1
        • Get-AzureRmDnsRecordSet -Name “@” -RecordType NS -Zone $zone
        • New-AzureRmDnsRecordSet  -Name abc  -ZoneName abc.com -ResourceGroupName rg1  –RecordType A -DnsRecords (New-AzureRmDnsRecordConfig -Ipv4Address “1.2.3.4“)
        • Resolve-DnsName -Server ns1-07.azure-dns.com -Name abc.com 
    • Virtual Machines/VMs:
      • Create a basic VM (latest Windows Server 2016):
        # Login to Azure
        Login-AzureRmAccount
        # Variables for common values
        $rg = “rg1”
        $loc = “EastUS”
        $vmName = “vm1”
        # Create user object
        $cred = Get-Credential -UserName “vmadmin” -Message “VM Administrator Password”
        # Create a resource group
        New-AzureRmResourceGroup -Name $rg -Location $loc
        # Create a virtual machine
        New-AzureRmVM `
        -ResourceGroupName $rg `
        -Location $loc `
        -Name $vmName `
        -Image “Win2016Datacenter” `
        -Size “Standard_B1s” `
        -Credential $cred `
        -VirtualNetworkName “vnet1” `
        -SubnetName “subnet1” `
        -SecurityGroupName “nsg1” `
        -PublicIpAddressName “ip1” `
        -OpenPorts 80,3389
        # Install IIS into VM
        $set = ‘{“commandToExecute”:”powershell Add-WindowsFeature Web-Server”}’
        Set-AzureRmVMExtension -ResourceGroupName $rg -Location $loc
        -VMName $vmName -ExtensionName “IIS” -Publisher “Microsoft.Compute” -ExtensionType “CustomScriptExtension” -TypeHandlerVersion 1.4 -SettingString $set
        #Connect to VM
        Get-AzureRmPublicIpAddress
        -ResourceGroupName “rg1” | Select IpAddress
        mstsc  /v:<publicIpAddress>
      • Create a detailed VM (Windows Server 2016 Core):
        $locName = “eastus”
        $rgName = “rg1”
        $nsgName = “nsg1”
        $ruleName = “AllowRDP”
        $port = “3389”
        $vnetName = “vnet1”
        $vnetAddress = “10.0.0.0/16”
        $subnetName = “vnet1-subnet”
        $subnetAddress = “10.0.1.0/24”
        $ipName = “vm1-ip”
        $nicName = “vm1-nic”
        $vmName = “vm1”
        $vmAdmin = “vmadmin”
        $password = “Pa55word5”
        $vmSize = “Standard_B1s”
        $vmSkus = “2016-Datacenter-Server-Core-smalldisk”
        $vmOffer = “WindowsServer”
        $vmPublisher = “MicrosoftWindowsServer”
        $vmVersion = “latest”#Login to Azure
        Login-AzureRmAccount#Create Resource group
        New-AzureRmResourceGroup -Name $rgName -Location $locName#Create Network Security Group and rule
        $rule = New-AzureRmNetworkSecurityRuleConfig -Name $ruleName -Priority 600 `
        -Access Allow -Protocol * -Direction Inbound `
        -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange $port
        $nsg = New-AzureRmNetworkSecurityGroup -ResourceGroupName $rgName -Location $locName -Name $nsgName -SecurityRules $rule
        #Create Virtual network
        $subnet = New-AzureRmVirtualNetworkSubnetConfig -AddressPrefix $subnetAddress -Name $subnetName -NetworkSecurityGroup $nsg
        $vnet = New-AzureRmVirtualNetwork -ResourceGroupName $rgName -Location $locName -Name $vnetName -AddressPrefix $vnetAddress -Subnet $subnet
        # Create Public IP and Network Interface Card
        $ip = New-AzureRmPublicIpAddress -ResourceGroupName $rgName -Location $locName -Name $ipName -AllocationMethod Dynamic
        $nic = New-AzureRmNetworkInterface -ResourceGroupName $rgName -Location $locName -Name $nicName -SubnetId $vnet.Subnets[0].Id -PublicIpAddressId $ip.Id#Get Windows Administrator credentials
        #$cred = Get-Credential -UserName $vmAdmin -Message “Password?”
        $secPassword = ConvertTo-SecureString $password -AsPlainText -Force
        $credentials = New-Object System.Management.Automation.PSCredential ($vmAdmin $secPassword)#Create VM Config
        $vm = New-AzureRmVMConfig -VMName $vmName -VMSize $vmSize
        $vm = Set-AzureRmVMOperatingSystem -VM $vm -Windows -ComputerName $vmName -Credential $credentials
        $vm = Add-AzureRmVMNetworkInterface -VM $vm -Id $nic.Id
        $vm = Set-AzureRmVMOSDisk -VM $vm -Name “$vmName.vhd” -CreateOption FromImage
        $vm = Set-AzureRmVMBootDiagnostics -VM $vm -Disable
        $vm = Set-AzureRmVMSourceImage -VM $vm -Skus $vmSkus -PublisherName “MicrosoftWindowsServer” -Offer “WindowsServer” -Version “latest”#Deploy VM
        New-AzureRmVM -ResourceGroupName $rgName -Location $locName -VM $vm$secPassword = ConvertTo-SecureString $password -AsPlainText -Force
        $credentials = New-Object System.Management.Automation.PSCredential ($vmAdmin $secPassword)
  • Powershell Desired State Configuration (DSC): A declarative technology enabling the definition of what a system should be without having to detail how to make it that way.
    • Without DSC:
      Import-Module ServerManager
      If (-not (Get-WindowsFeature “Web-Server”).Installed) {
      try {
      Add-WindowsFeature Web-Server
      }
      catch {
      Write-Error $_
      }
      }
    • With DSC:
      Configuration WebConfig {
      param([string[]]$computerName=”localhost”)
      Node $comptuerName {
      WindowsFeature WebServer {
      Ensure = “Present”
      Name = “Web-Server”
      }
      }
      }
  • Azure CLI 2.0
    • az login|logout
    • az account [list|show|list-locations|set –subscription <ID>] -o table
    • az provider [list|show –namespace Microsoft.Compute] -o table|tsv
    • az group [list|show -n rg1  –query tags|export -n rg1]
    • az group create -n rg1  -l eastus
    • az group update -n rg1  –set tags.Owner=User1  tags.Dept=IT
    • az resource [list {-g rg1}|show] -o table
    • az vm list [-g rg1]
    • az vm create -n vm1 -g rg1 –image UbuntuLTS
    • az vm show –resource-group rg1 –name vm1 –show-details –query [fqdns] –output tsv)
    • az vm reset-access  -g rg  -n vm1  –u LinuxAdmin  -p  NewPassw0rd2
    • az vm availability-set create
    • az network vnet create –resource-group rg1 –location EastUS –name vnet1 –address-prefix 10.0.0.0/16 –subnet-name subnet1 –subnet-prefix 10.0.1.0/24
    • az network vnet subnet create -g rg1 –vnet-name vnet1 -n Subnet2 –address-prefix 10.0.2.0/24
    • az network dns record-set ns show –resource-group rg1 –zone-name abc.com –name @
    • az provider register -n Microsoft.ContainerService
    • Azure Container Service (AKS):
      • az aks create –resource-group rg1 –name k8scluster –node-count 1 –node-vm-size Standard_B1s –generate-ssh-keys
      • az aks get-credentials –resource-group rg1 –name k8scluster
      • az aks kubernetes get-credential
      • kubectl get nodes; kubectl create -f test.yaml
    • Azure Container Registry:
      • az acr list -o table
      • az acr show -n reg1 –query loginServer
      • az acr credential show -n reg1 –query passwords[0].value

Reference:

 

Advertisements

About Ishtiaque

I am IBM Certified Infrastructure Systems Architect, Linux Foundation Certified System Administrator, Oracle Certified Programmer in Java and Web Component Developer, and TOGAF 9 certified with over 10 years of support and development experience in IBM middleware software and Java. Additionally, have a sound grip in databases and OpenStack administration. I hold the following certifications: IBM Certified Infrastructure Systems Architect Linux Foundation Certified System Administrator (LFCS) TOGAF 9 Certified Oracle Certified Expert, Java EE6 Web Component Developer Oracle Certified Professional – Java 6 Programmer ITIL v3 Foundation Certified IBM Certified Solution Architect – Cloud Computing Infrastructure V1 IBM Certified System Administrator – WebSphere Portal V8, V7, V6.1, V6 IBM Certified System Administrator – WebSphere Application Server V7, V6.1 IBM Certified System Administrator – AIX V7 IBM Certified System Administrator – WebSphere MQ V7 IBM Certified Deployment Professional – Business Process Manager Advanced V7.5 IBM Certified Solution Advisor – Cloud Computing Architecture V3 IBM Certified Solution Developer – WebSphere Portal V5.1
This entry was posted in azure. Bookmark the permalink.