Wednesday, 21 December 2016

Connect to Office 365 using PowerShell

Connect to Office 365 using PowerShell


Step 1: Install required software

These steps are required once on your computer, not every time you connect. However, you'll likely need to install newer versions of the software periodically.

1.      Install the 64-bit version of the Microsoft Online Services Sign-in Assistant: Microsoft Online Services Sign-in Assistant for IT Professionals RTW.

2.      Install the 64-bit version of the Windows Azure Active Directory Module for Windows PowerShell: Windows Azure Active Directory Module for Windows PowerShell (64-bit version).

Step 2: Open the Windows Azure Active Directory Module


1.      Find and open the Windows Azure Active Directory Module for Windows PowerShell by using one of the following methods based on your version of Windows:
o    Start menu   On the Start menu, enter Azure in the Search programs and files box.
o    No Start menu   Search for Azure using any of these methods:
o    On the Start screen, click an empty area, and type Azure.
o    On the desktop or the Start screen, press the Windows key+Q. In the Search charm, type Azure.
o    On the desktop or the Start screen, move your cursor to the upper-right corner, or swipe left from the right edge of the screen to show the charms. Select the Search charm, and enter Azure.

2.      In the results, select Windows Azure Active Directory Module for Windows PowerShell.

Or you can start -à Powershell ISE

Step 3: Connect to your Office 365 subscription


1.      In the Windows Azure Active Directory Module for Windows PowerShell, run the following command.

2.  $Cred = Get-Credential

In the Windows PowerShell Credential Request dialog box, type your Office 365 work or school account user name and password, and then click OK.

3.      Run the following command.

4.  Connect-MsolService -Credential $Cred

5.  Import-Module MSOnline

6.  Set-ExecutionPolicy RemoteSigned -Force

7.  $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ `
-Credential $Cred -Authentication Basic -AllowRedirection


8.  Import-PSSession $Session -AllowClobber

Moving Azure Resources from one Subscription to Another in Same Tenant


Moving Azure Resources from one Subscription to Another in Same Tenant


Login-AzureRmAccount

Get-AzureRmSubscription

$subsId=Select-AzureRmSubscription -SubscriptionId "your Subscription ID xxxxx"

Get-AzureRMResource -ResourceName "Source Resource_Name" -ResourceGroupName "Source_Resource_Group"

Move-AzureRMResource -DestinationResourceGroupName "Resource_Move" -DestinationSubscriptionId "Destination Subscription ID xxxxx"



Note: This works only if both the subscriptions are under in same Tenant ID.

Powershell Script to view / check the status of VMs in a Subscription



Powershell Script to view / check the status of VMs in a Subscription



Login-AzureRmAccount

$RGs = Get-AzureRMResourceGroup

foreach($RG in $RGs)
{
    $VMs = Get-AzureRmVM -ResourceGroupName $RG.ResourceGroupName
    foreach($VM in $VMs)
    {
        $VMDetail = Get-AzureRmVM -ResourceGroupName $RG.ResourceGroupName -Name $VM.Name -Status
        foreach ($VMStatus in $VMDetail.Statuses)
        {
            #if($VMStatus.Code.CompareTo("PowerState/deallocated") -eq 0)
            if($VMStatus.Code -like "PowerState/*")
            {
                $VMStatusDetail = $VMStatus.DisplayStatus
            }
        }
        write-output $VM.Name $VMStatusDetail
    }
}



Automation PS Workflow to Start or Stop VMs Simultaneously

#PowerShell Script to Create Automation Account and Import RunBook!

Run Book which will start or stop VMs Simultaneously 


#Select-AzureRmProfile -Path 'C:\Users\gulab\Desktop\Text\Azure Scripts\Login\hotmail.txt'

Login-AzureRmAccount

$ResourceGroup = "Automation-SorStVMs"
$AutomationAcct = "cloudsupport"
$runbookName = "startORstop"
$scheduleName1 = "Start"
$scheduleName2 = "Stop"

New-AzureRmResourceGroup -Name $ResourceGroup -Location 'southeastasia'

New-AzureRmAutomationAccount -Name $AutomationAcct -ResourceGroupName $ResourceGroup -Location 'southeastasia'

New-AzureRmAutomationRunbook -Name startORstop -Type PowerShellWorkflow `
-Description "Start or Stop all VMs in a Subscription Parallely" `
-ResourceGroupName $ResourceGroup -AutomationAccountName $AutomationAcct


#Import-AzureRmAutomationRunbook -AutomationAccountName $AutomationAcct `
#-ResourceGroupName $ResourceGroup -Path 'C:\Users\gulab\Desktop\Text\Azure Scripts\startORstop.ps1' `
#-Type PowerShellWorkflow -Description "Parallel Start or Stop All VMs"


#Once you are done creating empty RunBook, copy the below attached .ps workflow script into empty RunBook and save the runbook.


#################################################################################


workflow startORstop
{
   Param
    (

        [Parameter(Mandatory=$true)]
        [String]
        $ResourceGroupName = '*',

        [Parameter(Mandatory=$true)]
        [Boolean]
        $Shutdown
    )
    $connectionName = "AzureRunAsConnection"
    try
    {
    
        # Get the connection "AzureRunAsConnection "
        $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName         

        "Logging in to Azure..."
        Add-AzureRmAccount `
            -ServicePrincipal `
            -TenantId $servicePrincipalConnection.TenantId `
            -ApplicationId $servicePrincipalConnection.ApplicationId `
            -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 
    }
    catch 
    {
        if (!$servicePrincipalConnection)
        {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
        } 
        else
        {
        Write-Error -Message $_.Exception
        throw $_.Exception
        }
    }

    If ($ResourceGroupName -eq '*')
    {
        $vms = Get-AzureRmVM
        Foreach -Parallel ( $vm in $vms ) 
        {
                        
            if ( $Shutdown ) 
            {
                Write-Output "Stopping $($vm.Name)";              
                Stop-AzureRmVm -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Force;
            }

            else 
            {
                Write-Output "Starting $($vm.Name)";                
                Start-AzureRmVm -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName;
            }
        }

    }
    
    Else
    {
        $vms = Get-AzureRmVM -ResourceGroupName $ResourceGroupName;   

        Foreach -Parallel ( $vm in $vms ) 
        {                        
            if ( $Shutdown ) 
            {
                Write-Output "Stopping $($vm.Name)";              
                Stop-AzureRmVm -Name $vm.Name -ResourceGroupName $ResourceGroupName -Force;
            }

            else 
            {
                Write-Output "Starting $($vm.Name)";                
                Start-AzureRmVm -Name $vm.Name -ResourceGroupName $ResourceGroupName;
            }
        }
    }

}

#################################################################################




Publish-AzureRmAutomationRunbook -ResourceGroupName $ResourceGroup -AutomationAccountName $AutomationAcct -Name "startORstop"


New-AzurermAutomationSchedule –AutomationAccountName $AutomationAcct `
–Name $scheduleName1 –StartTime "11/26/2016 08:45:00 AM" -TimeZone "UTC+05:30" `
–DayInterval 1 -ResourceGroupName $ResourceGroup -Description "Parallel Start all VMs"


New-AzurermAutomationSchedule –AutomationAccountName $AutomationAcct `
–Name $scheduleName2 –StartTime "11/26/2016 07:00:00 PM" -TimeZone "UTC+05:30" `
–DayInterval 1 -ResourceGroupName $ResourceGroup -Description "Parallel Stop all VMs"
To link a schedule to a runbook with the Azure Portal to Start VMs
1.      In the Azure portal, from your automation account, click the Runbooks tile to open the Runbooks blade.
2.      Click on the name of the runbook to schedule.
3.      Click on Schedule Tile
4.      If the runbook is not currently linked to a schedule, then you will be given the option to create a new schedule or link to an existing schedule (Start).
5.      Click on Add a Schedule à Schedule (Link a schedule to your runbook) à Select the Existing Schedule (Start)
6.      The runbook has parameters, you can select the option à Click Configure Parameters and Run Settings à RESOURCEGROUPNAME “Leave it” Blank à Shutdown (Select False), and OK & OK to Link your schedule with your runbook.



To link a schedule to a runbook with the Azure Portal to Stop VMs
7.      In the Azure portal, from your automation account, click the Runbooks tile to open the Runbooks blade.
8.      Click on the name of the runbook to schedule.
9.      Click on Schedule Tile
10.  If the runbook is not currently linked to a schedule, then you will be given the option to create a new schedule or link to an existing schedule (Stop).
11.  Click on Add a Schedule à Schedule (Link a schedule to your runbook) à Select the Existing Schedule (Stop)
12.  The runbook has parameters, you can select the option à Click Configure Parameters and Run Settings à RESOURCEGROUPNAME “Leave it” Blank à Shutdown (Select True), and OK & OK to Link your schedule with your runbook.




Monday, 19 December 2016

List out AzureRM Operating Systems available

#Below command lists the Image Publishers available in the Specified location
Get-AzureRmVMImagePublisher -Location 'Southindia'

#Below command lists the Offer(offer means Windows flavour category) available with the Publishername
Get-AzureRmVMImageOffer -Location 'Southindia' -PublisherName 'MicrosoftWindowsServer'

#Below command lists the available SKU's under windows server
Get-AzureRmVMImagesku -Location 'Southindia' -PublisherName 'MicrosoftWindowsServer' -Offer 'windowsserver'

#Below command lists the version of the sku
Get-AzureRMVMImage -location 'Southindia' -publisherName "MicrosoftWindowsServer" -sku "2012-R2-Datacenter" -Offer 'windowsserver'

#Below Command lists the detials of the particual sku.
Get-AzureRMVMImage -location 'Southindia' -publisherName "MicrosoftWindowsServer" -sku "2012-R2-Datacenter" -Offer 'windowsserver' -Version '4.0.20161214'

Monday, 24 October 2016

Deploying Windows VM from custom image using Powershell.




How you can deploy a Windows Machine from your source VM image. We have plenty of methods using that we can deploy the VM. Like CLI, Powershell, using Json template.

Here we use Powershell Method to deploy the machine. First thing upload your source VHD image to the cloud. Microsoft Azure support only VHD, If you have image in the form of VHDX or any other format then you need to convert it before uploading.

Convert VHDX to VHD Using Powershell.
Copy paste the below commands in your powershell ISE.

Convert-VHD -Path "d:\sourcecimage.vhdx" -DestinationPath "Sourceimage.vhd"

Once the conversion completed. Upload it to your azure cloud.

Then Now we start the deployment from source image. Copy past the below command to you powershell ISE for deploy. Modify the Global variable as per your wish.

#Deploy New VM using Your custom VM
# Sign-in with Azure account credentials
Login-AzureRmAccount
# Select your Azure Subscription.
#Select your subscription ID
$subscriptionId =
    (Get-AzureRmSubscription |
     Out-GridView `
        -Title "Select an Azure Subscription ..." `
        -PassThru).SubscriptionId
Select-AzureRmSubscription `
    -SubscriptionId $subscriptionId
## Global Variables
$ResourceGroupName = "dstresourcegrp"
$location = "Southeastasia"
## Storage
$storageName = "dststorage"
# Machine Type you want to create.
$storageType = "Standard_A1"
## Network
$nicname = "dstnic"
$subnetName = "dstsubnet"
$vnetName = "dstvnet"
$vnetAddressPrefix = "10.0.0.0/16"
$vnetSubnetAddressPrefix = "10.0.0.0/24"
$publicIPName = "dstpip"
## Compute
$vmName = "dstvm"
$computerName = "dstcomputer"
$vmSize = "Standard_A1"
$osDiskName = $vmName + "osDisk"

#Create New Resouce Group
New-AzureRmResourceGroup -Name $ResourceGroupName -Location $location
#Create New Storage and put in variable
$storageAcc = New-AzureRmStorageAccount -ResourceGroupName $ResourceGroupName -Name $storageName -SkuName "Standard_LRS" -Kind "Storage" -Location $location
#Create a virtual network
$singleSubnet = New-AzureRmVirtualNetworkSubnetConfig -Name $subnetName -AddressPrefix $vnetSubnetAddressPrefix
$vnet = New-AzureRmVirtualNetwork -Name $vnetName -ResourceGroupName $ResourceGroupName -Location $location -AddressPrefix $vnetAddressPrefix -Subnet $singleSubnet
#Create a public IP address and network interface
$pip = New-AzureRmPublicIpAddress -Name $publicIPName -ResourceGroupName $ResourceGroupName -Location $location -AllocationMethod Dynamic
$nic = New-AzureRmNetworkInterface -Name $nicname -ResourceGroupName $ResourceGroupName -Location $location -SubnetId $vnet.Subnets[0].Id -PublicIpAddressId $pip.Id
#Create a virtual machine
#The password must be at 12-123 characters long and have at least one lower case character, one upper case character, one number, and one special character.
$cred = Get-Credential -Message "Type the name and password of the local administrator account."
$vm = New-AzureRmVMConfig -VMName $vmName -VMSize $vmSize
$vm = Set-AzureRmVMOperatingSystem -VM $vm -Windows -ComputerName $computerName -Credential $cred -ProvisionVMAgent -EnableAutoUpdate
$vm = Add-AzureRmVMNetworkInterface -VM $vm -Id $nic.Id
#Create New Os Disk uri
$osDiskUri = "https://srcstorage.blob.core.windows.net/vhds/newosdisk.vhd"
#Image URI you can Find Storage group --> Blob --> System -->Microsoft.Compute -->Images --> your conntainer Name --> vhd name given while caputure VM.
$imageUri = "https://srcstorage.blob.core.windows.net/system/Microsoft.Compute/Images/customvhd/Lovlyimg-osDisk.a2d499b8-42b4-4fca-83cf-8403d759435b.vhd"
$vm = Set-AzureRmVMOSDisk -VM $vm -Name $osDiskName -VhdUri $osDiskUri -CreateOption FromImage -SourceImageUri $imageUri  -Caching ReadWrite -Windows
#running below command you can see your VM attached parameters.
$vm
#Create the new VM
New-AzureRmVM -ResourceGroupName $ResourceGroupName -Location $location -VM $vm

Get SSL Certificate Expiry Notification on Mail.

 There are multiple ways to get SSL Certification expiry details/alert. We all know if our SSL certificate get expire, how critical situatio...