Wednesday, January 16, 2019

Adding a disk to Azure vm using powershell

Powershell Script to add a disk to Azure RM virtual machine.

$Credentials = Get-Credential
param([string] $VirtualMachineName,$DiskSize)

Login-AzureRmAccount -EnvironmentName AzureUSGovernment -Credential $Credentials

$Managed_Prod_Sub = Get-AzureRMSubscription -SubscriptionId "Your subscription id"
Select-AzureRMSubscription -SubscriptionId $Managed_Prod_Sub.SubscriptionId ##
$Managed_ProdVMS = Get-AzureRMVM


if($VM.name -eq $VirtualMachineName)
  {
  Write-host "Working on $($VM.name)" -ForegroundColor Yellow
     $rgName = $VM.ResourceGroupName
    $vmName = $VM.Name
    $location = $VM.location
    $storageType = 'Premium_LRS'
    $dataDiskName = $vmName + '_datadisk1'

   
    $diskConfig = New-AzureRmDiskConfig -AccountType PremiumLRS -Location $location -CreateOption Empty -DiskSizeGB $DiskSize -OsType Windows

    $dataDisk1 = New-AzureRmDisk -DiskName $dataDiskName -Disk $diskConfig -ResourceGroupName $rgName
   
    $vm = Get-AzureRmVM -Name $vmName -ResourceGroupName $rgName
    $vm = Add-AzureRmVMDataDisk -VM $vm -Name $dataDiskName -CreateOption Attach -ManagedDiskId $dataDisk1.Id -Lun 1

    Update-AzureRmVM -VM $vm -ResourceGroupName $rgName


   }

Wednesday, January 9, 2019

Good trick for using Try Catch in Powershell

    try{

 Something......

    }

    Catch{
$formatstring = "{0} : {1}`n{2}`n" +
                "    + CategoryInfo          : {3}`n" +
                "    + FullyQualifiedErrorId : {4}`n"
$fields = $_.InvocationInfo.MyCommand.Name,
          $_.ErrorDetails.Message,
          $_.InvocationInfo.PositionMessage,
          $_.CategoryInfo.ToString(),
          $_.FullyQualifiedErrorId

Out-File -FilePath 'C:\Temp\error.txt' -inputobject ($formatstring -f $fields) -Append
 
  }
   

Tuesday, December 11, 2018

Get Azure VM status and ip address

Powershell script to get the list of virtual machines in Azure Gov with ip address.

$username = "parag.waghmare@contoso.com"
$Password = "Password"
$Credentials = New-Object System.Management.Automation.PSCredential ($username, $password)
Login-AzureRmAccount -EnvironmentName AzureUSGovernment -Credential $Credentials 
$subs = Get-AzureRmSubscription 
foreach ($Sub in $Subs) { 
   
    $SelectSub = Select-AzureRmSubscription -SubscriptionName $Sub.Name 

    $nics = get-azurermnetworkinterface | where VirtualMachine -NE $null #skip Nics with no VM


    $VMs = Get-AzureRMVM -Status

    foreach($nic in $nics)
{
    $vm = $vms | where-object -Property Id -EQ $nic.VirtualMachine.id
    $prv =  $nic.IpConfigurations | select-object -ExpandProperty PrivateIpAddress
    $alloc =  $nic.IpConfigurations | select-object -ExpandProperty PrivateIpAllocationMethod
    $data = $Sub.Name + "`t "+ $vm.Name + "`t "+ $prv + "`t "+ $alloc  + "`t " + $Vm.powerstate 
    Write-Host $data 
}