Manage Office 365 Roles membership

Hello, I’am sharing with you how to  manage Roles in Office 365 using PowerShell. It can be helpful for Office 365 administrators. The topics covered in this post are :

  • List all administrative roles of your Office 365 tenant
  • Find a user administrative role
  • List a role members
  • Add members to a role
  • Remove members from a role
  • Export Role member in a csv file

Ready, let’s go now…

First of all, connect to your Office 365 tenant

PS C:\> Connect-MsolService

If you don’t have PowerShell Module for Office 365 installed, follow this link.

List all administrative roles of your Office 365 tenant

PS C:\> Get-MsolRole

ObjectId                               Name                             Description                                                                                                         
--------                               ----                             -----------                                                                                                         
729827e3-9c14-49f7-bb1b-9608f156bbb8   Helpdesk Administrator           Can reset passwords for non-administrators and Helpdesk Administrators.                                             
f023fd81-a637-4b56-95fd-791ac0226033   Service Support Administrator    Can read service health information and manage support tickets.                                                     
b0f54661-2d74-4c50-afa3-1ec803f12efe   Billing Administrator            Can perform common billing related tasks like updating payment information.                                         
4ba39ca4-527c-499a-b93d-d9b492c50246   Partner Tier1 Support            Do not use - not intended for general use.                                                                          
e00e864a-17c5-4a4b-9c06-f5b95a8d5bd8   Partner Tier2 Support            Do not use - not intended for general use.                                                                          
88d8e3e3-8f55-4a1e-953a-9b9898b8876b   Directory Readers                Can read basic directory information. For granting access to applications, not intended for users.                  
29232cdf-9323-42fd-ade2-1d097af3e4de   Exchange Service Administrator   Can manage all aspects of the Exchange product.                                                                     
75941009-915a-4869-abe7-691bff18279e   Lync Service Administrator       Can manage all aspects of the Skype for Business product.                                                           
fe930be7-5e62-47db-91af-98c3a49a38b1   User Account Administrator       Can manage all aspects of users and groups, including resetting passwords for limited admins.                       
9360feb5-f418-4baa-8175-e2a00bac4301   Directory Writers                Can read and write basic directory information. For granting access to applications, not intended for users.        
62e90394-69f5-4237-9190-012177145e10   Company Administrator            Can manage all aspects of Azure AD and Microsoft services that use Azure AD identities.                             
f28a1f50-f6e7-4571-818b-6a12f2af6b6c   SharePoint Service Administrator Can manage all aspects of the SharePoint service.                                                                   
d405c6df-0af8-4e3b-95e4-4d06e542189e   Device Users                     Device Users                                                                                                        
9f06204d-73c1-4d4c-880a-6edb90606fd8   Device Administrators            Device Administrators                                                                                               
9c094953-4995-41c8-84c8-3ebb9b32c93f   Device Join                      Device Join                                                                                                         
c34f683f-4d5a-4403-affd-6615e00e3a7f   Workplace Device Join            Workplace Device Join                                                                                               
17315797-102d-40b4-93e0-432062caca18   Compliance Administrator         Can read and manage compliance configuration and reports in Azure AD and Office 365.                                
d29b2b05-8046-44ba-8758-1e26182fcf32   Directory Synchronization Acc... Only used by Azure AD Connect service.                                                                              
2b499bcd-da44-4968-8aec-78e1674fa64d   Device Managers                  Deprecated - Do Not Use.                                                                                            
9b895d92-2cd3-44c7-9d02-a6ac2d5ea5c3   Application Administrator        Can create and manage all aspects of app registrations and enterprise apps.                                         
cf1c38e5-3621-4004-a7cb-879624dced7c   Application Developer            Can create application registrations independent of the 'Users can register applications' setting.                  
5d6b6bb7-de71-4623-b4af-96380a352509   Security Reader                  Can read security information and reports in Azure AD and Office 365.                                               
194ae4cb-b126-40b2-bd5b-6091b380977d   Security Administrator           Security Administrator allows ability to read and manage security configuration and reports.                        
e8611ab8-c189-46e8-94e1-60213ab1f814   Privileged Role Administrator    Can manage role assignments in Azure AD, and all aspects of Privileged Identity Management.                         
3a2c62db-5318-420d-8d74-23affee5d9d5   Intune Service Administrator     Can manage all aspects of the Intune product.                                                                       
158c047a-c907-4556-b7ef-446551a6b5f7   Cloud Application Administrator  Can create and manage all aspects of app registrations and enterprise apps except App Proxy.                        
5c4f9dcd-47dc-4cf7-8c9a-9e4207cbfc91   Customer LockBox Access Approver Can approve Microsoft support requests to access customer organizational data.                                      
44367163-eba1-44c3-98af-f5787879f96a   CRM Service Administrator        Can manage all aspects of the Dynamics 365 product.                                                                 
a9ea8996-122f-4c74-9520-8edcd192826c   Power BI Service Administrator   Can manage all aspects of the Power BI product.                                                                     
95e79109-95c0-4d8e-aee3-d01accf2d47b   Guest Inviter                    Can invite guest users independent of the 'members can invite guests' setting.                                      
b1be1c3e-b65d-4f19-8427-f6fa0d97feb9   Conditional Access Administrator Can manage conditional access capabilities.                                                                         
4a5d8f65-41da-4de4-8968-e035b65339cf   Reports Reader                   Can read sign-in and audit reports.                                                                                 
790c1fb9-7f7d-4f88-86a1-ef1f95c05c1b   Message Center Reader            Can read messages and updates for their organization in Office 365 Message Center only.                             
7495fdc4-34c4-4d15-a289-98788ce399fd   Information Protection Admini... Can manage all aspects of the Azure Information Protection product.                                                 
4d6ac14f-3453-41d0-bef9-a3e0c569773a   License Administrator            Can manage product licenses on users and groups.                                                                    
7698a772-787b-4ac8-901f-60d6b08affd2   Cloud Device Administrator       Full access to manage devices in Azure AD.                                                                          
10dae51f-b6af-4016-8d66-8c2a99b929b3   Guest User                       Default role for guest users. Can read a limited set of directory information.

Find a user administrative role

PS C:\> Get-MsolUserRole -UserPrincipalName user1@mydomain.com

ObjectId                               Name                             Description                                                                                                         
--------                               ----                             -----------                                                                                                         
62e90394-69f5-4237-9190-012177145e10   Company Administrator            Can manage all aspects of Azure AD and Microsoft services that use Azure AD identities.

List a role members

Get the role objectId

PS C:\> $role = Get-MsolRole -RoleName "User account Administrator"
PS C:\> $role.ObjectId 
Guid                                
----                                
fe930be7-5e62-47db-91af-98c3a49a38b1

Get role members

PS C:\> Get-MsolRoleMember -RoleObjectId $role.ObjectId

RoleMemberType EmailAddress                   DisplayName                        isLicensed
-------------- ------------                   -----------                        ----------
User           user2@mydomain.com             user2                      	 True      
User           user3@mydomain.com             user3                    		 True      
User           user4@mydomain.com             user4                    		 False

Add member to a role

PS C:\> Add-MsolRoleMember -RoleObjectId $role.ObjectId -RoleMemberEmailAddress user5@mydomain.com

Remove member from a Role

PS C:\> Remove-MsolRoleMember -RoleObjectId $role.ObjectId -RoleMemberEmailAddress user3@mydomain.com

Check member removal

PS C:\> Get-MsolRoleMember -RoleObjectId $role.ObjectId

RoleMemberType EmailAddress                   DisplayName                        isLicensed
-------------- ------------                   -----------                        ----------
User           user2@mydomain.com             user2                      	 True      
User           user4@mydomain.com             user4                    		 False      
User           user5@mydomain.com             user5                   		 False

To export Role member in a csv file, use the below command

PS C:\> Get-MsolRoleMember -RoleObjectId $role.ObjectId | Export-Csv -Path C:\MyRoleMembers.csv -Encoding UTF8 -Delimiter ";"

Voilà 🙂

Allocate licenses in bulk to your Office 365 users (Option 1 : Using PowerShell)

As an Office 365 IT professional, you may need to allocate license to users. There are several ways for doing that. Here, I will show you two ways to achieve your goal.

  • Option 1 : Allocate licenses in bulk to your Office 365 users using PowerShell
  • Option 2 : Allocate licenses in bulk to your Office 365 users using Azure Active Directory group membership

Option 1 : Allocate licenses in bulk to your Office 365 users using PowerShell

Below is the script I’m sharing with you.

Function Set-o365UsersLicense{

  [CmdletBinding()]
  Param(
    [Parameter(mandatory=$true)]$upnPath,                                 #Path to the .csv file containing users UserPrincipalName
    [Parameter(mandatory=$false)]$LicensePlan = "E1",                     #Office 365 License Plan to be allocated to users
    [Parameter(mandatory=$false)]$DisabledOptions = "YAMMER_ENTERPRISE",  #Disabled Feature
    [Parameter(mandatory=$true)]$LogPath = "c:\"                          #Logs path
  )

  $Error.Clear()
  $LicenseToAdd = $Null
  $DisableYammer = $False
  $LicenseOptions = @()

  #Finding License Plan to activate
  Switch($LicensePlan){
    "E1" { 
        Write-host "You chosed Plan E1" -ForegroundColor Green
        $LicenseToAdd = "kingo:STANDARDPACK" 
        $LicenseToRemove = "kingo:ENTERPRISEPACK","kingo:WACONEDRIVESTANDARD" 
    }
   "E3" {
        Write-host "You chosed Plan E3" -ForegroundColor Green
        $LicenseToAdd = "kingo:ENTERPRISEPACK" 
        $LicenseToRemove = "kingo:STANDARDPACK","kingo:WACONEDRIVESTANDARD" 
    }
   "OD" {
        Write-host "You chosed To assign OneDrive" -ForegroundColor Green
        $LicenseToAdd = "kingo:WACONEDRIVESTANDARD" 
        $LicenseToRemove = "kingo:STANDARDPACK","kingo:ENTERPRISEPACK" 
    }
    Default { 
        Write-Host "$LicensePlan is not a valid License Plan parameter !" -ForegroundColor Red
    }
  }

  #Importing users to be assigned License
  $upns = Import-Csv $upnPath

  #Checking Licenses availability
  $MsolAccountSku = Get-MsolAccountSku | ? {$_.AccountSkuId -ilike $LicenseToAdd}
  $AvailableLics = $MsolAccountSku.ActiveUnits - $MsolAccountSku.ConsumedUnits

  #Assigning License to user
  If($AvailableLics -ge $upns.Count){

    #Creating not existing upns log file
    "Not existing upn List" > $($LogPath + "Upns_Not_Exist.log.log")

    #Defining License options to disable
    if($DisabledOptions -in $MsolAccountSku.ServiceStatus.ServicePlan.ServiceName){
      $LicenseOptions = New-MsolLicenseOptions -AccountSkuId $LicenseToAdd -DisabledPlans $DisabledOptions
    }

    #Enabling users Licenses
    $upns | % {

      #Checking if user exists before processing with licensing
      $_.UserPrincipalName
      If($User = Get-MsolUser -UserPrincipalName $_.UserPrincipalName -ErrorAction SilentlyContinue){

        #Getting current user Licenses
        $CurrentUserLicenses = $User.Licenses.AccountSkuId

        #Removing unecessary Licenses
        $LicenseToRemove | %{
          if($CurrentUserLicenses -contains $_){ 
            Set-MsolUserLicense -UserPrincipalName $User.UserPrincipalName -RemoveLicenses $_
          }
        }

        #Assigning New License to user if not already enabled
        If($CurrentUserLicenses -notcontains $LicenseToAdd){

          #Disable YAMMER if License to add is plan E1, E3
          If($LicenseOptions){
            Set-MsolUserLicense -UserPrincipalName $User.UserPrincipalName -AddLicenses $LicenseToAdd -LicenseOptions $LicenseOptions -EA SilentlyContinue
          }
          Else{
            Set-MsolUserLicense -UserPrincipalName $User.UserPrincipalName -AddLicenses $LicenseToAdd
          }
        }
      }
      Else{
        #Logging inexisting user account
        $User.UserPrincipalName >> $($LogPath + "Upns_Not_Exist.log")
      }
    }
  }
  Else{
    Write-Host "There are $AvailableLics $LicensePlan Licenses available" -ForegroundColor Red
    Write-Host "Please reduce users list to match available Licenses or Increase available Licenses" -ForegroundColor Red
  }

  #Exporting errors log
  $Error > $($LogPath + "Set_AzureUserLicense_Error.log")
  Write-Host "Script Logs Location : $LogPath " -ForegroundColor Yellow
}

A little description about the script parameters is necessary :

$upnPath : is the full path of the .csv file containing users upns

$LicensePlan : specify the license plan you want to configure

  • E1 : Office 365 Enterprise E1
  • E3 : Office 365 Enterprise E3
  • E5 : Office 365 Enterprise E5
  • OD : OneDrive Entreprise (Plan 1)

$DisabledOptions : specify the license feature you want to disable.  “YAMMER_ENTERPRISE” : designate Yammer as the feature to disable

$LogPath = designate the directory path where to save log files

“kingo” : refer to the name of my Office 365 tenant : kingo.onmicrosoft.com

The upns (UserPrincipalName) csv file must be formated like below :

UserPrincipalName
user1@domain.com
user2@domain.com
user2@domain.com
user2@domain.com

Prerequisites for running the script :

  • You will need Office 365 Module For PowerShell
  • Connect to your Office 365 tenant using the command : Connect-MsolService

How to run the script ?

  • With default parameters 
Set-o365UsersLicense -upnPath c:\upns.csv  -LogPath "d:\"

Users will be allocated License E1 with YAMMER disabled, and the log file saved in d:\ path.

  • With full parameters 

If the default parameters does not suit you, you can run a complete command by specifying full parameters like below :

Set-o365UsersLicense -upnPath "c:\upns.csv" -LicensePlan E3 -DisabledOptions "YAMMER_ENTERPRISE" -LogPath "d:\"

To check that users are well assigned licenses, use my previous post Show-LicensesMatrix.

Et voilà… 🙂

Option 2 : Allocate licenses in bulk to your Office 365 users using Azure Active Directory group membership  (coming soon…)

Get your Office 365 users licenses

Hi, here I’m sharing with you a PowerShell script that can help you if you are working on Office 365.

If ever, you asked yourself one day,  how to quickly view the Office 365 licenses configuration for a group of users in your organization, here is a script that can help you achieve that goal.

How does it work :

Step 1 : Connect to Office 365 PowerShell using your Office 365 Admin account. Here is a tuto for that :  https://docs.microsoft.com/fr-fr/office365/enterprise/powershell/connect-to-office-365-powershell

Step 2 : Prepare the upns csv file

Open a .txt file and fill it with your users UserPrincipalNames like this :

UserPrincipalName
user1@domain.com
user2@domain.com
user2@domain.com
user2@domain.com

Once you are done, save the content as a .csv file.

Step 3 : When your are connected, Copy and pass the below script in your console, and press Enter.

Function Show-LicensesMatrix {

  [CmdLetBinding()]
  Param(
    [Parameter(mandatory=$false)]$upnPath = "C:\Scripts\upns.csv"
  )

  #License Plans correspondence table
  $LicensePlans = @{
    E1 = "kingo:STANDARDPACK" 
    E3 = "kingo:ENTERPRISEPACK" 
    E5 = "kingo:ENTERPRISEPREMIUM"
    OD = "kingo:WACONEDRIVESTANDARD"
  }

  $Us = @()
  $Users = Import-Csv $upnPath | % {Get-MsolUser -SearchString $_.userPrincipalName} 

  ForEach ($u in $Users) {
    #Initializing variables
    $E1 = $E3 = $E5 = $OD = $false

    #Getting user License Plans
    if ($u.Licenses.AccountSkuId -contains $LicensePlans.E1){$E1 = $true}
    if ($u.Licenses.AccountSkuId -contains $LicensePlans.E3){$E3 = $true}
    if ($u.Licenses.AccountSkuId -contains $LicensePlans.E5){$E5 = $true}
    if ($u.Licenses.AccountSkuId -contains $LicensePlans.OD){$OD = $true}

    $Us += New-Object -TypeName PSObject -Property @{ 
      UserPrincipalName = $u.userPrincipalName
      E1 = $E1
      E3 = $E3
      E5 = $E5
      OD = $OD
    }
  }
  $Us | ft userPrincipalName, E1,E3,E5,OD
}

You are ready, run the script now :

Run Show-LicenseMatrix1

The result will look like below :

Show-LicenceMatrix

The meaning of E1, E3, E5 and OD is :

  • E1 : Office 365 Enterprise E1
  • E3 : Office 365 Enterprise E3
  • E5 : Office 365 Enterprise E5
  • OD : OneDrive Entreprise (Plan 1)

“kingo” : refer to the name of my Office 365 tenant : kingo.onmicrosoft.com

Et voilà… 🙂

 

Export Office 365 users and their Licenses configurations

Office 365 provides several ways to see user assigned license plans. You can use the admin portal, Azure Powershell or PowerShell for Office 365.

The biggest question is how to see both assigned license plans, enabled license and disabled license features for many users ? Not easy to reach your goal when using the admin portal. The best way is to use PowerShell.

Here, I provide you an Office 365 Powershell script for exporting all your licensed users, with their assigned license plans, their enabled and disabled licenses options.

Function Export-UsersLicensesConfig {

    #License Plans correspondence table with friendly name
    
    $LicensePlan = @{         
              ##<companyname>:<Licenseplan> = <license plan friendly name>          
                      "koaf365:AAD_PREMIUM" = "AzureAD Premium Plan 1"             
                   "koaf365:AX7_USER_TRIAL" = "Dynamics AX7.0 TRIAL"         
                     "koaf365:DESKLESSPACK" = "OFFICE 365 F1"       
          "koaf365:DYN365_ENTERPRISE_P1_IW" = "Dynamics 365 Enterprise Plan1"   
              "koaf365:DYN365_RETAIL_TRIAL" = "Dynamics 365 CRM TRIAL"               
                              "koaf365:EMS" = "EMS_E3"             
                       "koaf365:EMSPREMIUM" = "EMS_E5"        
                   "koaf365:ENTERPRISEPACK" = "E3"             
                "koaf365:ENTERPRISEPREMIUM" = "E5"          
                        "koaf365:FLOW_FREE" = "Microsoft Flow"            
                      "koaf365:INTUNE_A_VL" = "Intune Volume License"        
                       "koaf365:MCOMEETADV" = "Skype For Business PSTN Conferencing"   
        "koaf365:MICROSOFT_BUSINESS_CENTER" = "Microsoft Business Center"          
                     "koaf365:POWER_BI_PRO" = "Power BI PRO"         
                "koaf365:POWER_BI_STANDARD" = "Power BI Standard"    
        "koaf365:POWERAPPS_INDIVIDUAL_USER" = "Powerapps Individual User"           
                  "koaf365:POWERAPPS_VIRAL" = "Microsoft PowerApps and Logic flows"        
                   "koaf365:PROJECTPREMIUM" = "Project Online Premium"        
                     "koaf365:STANDARDPACK" = "E1"                
                           "koaf365:STREAM" = "Stream"         
                "koaf365:VISIOONLINE_PLAN1" = "Visio Online Plan 1"           
              "koaf365:WACONEDRIVESTANDARD" = "OneDrive For Business Plan 1"       
                      "koaf365:WIN_DEF_ATP" = "Windows Defender Avanced Threat Protection"
    }
    
    #Initializing users licenses config table
    $Us = @()

    #Getting all users list    
    $Users = Get-MsolUser -All | ?{$_.isLicensed -eq $true}

    ForEach($u in $Users){          
   
        #Getting assigned user License Plans        
        $O365Licenses = @()        
        $u.Licenses.AccountSkuId | % {            
            $O365Licenses += $LicensePlan."$_"        
        }        
        $O365Licenses = [string]::Join(',',$O365Licenses)            
    
        #Getting user enabled license features        
        $EnabledFeature = ($u.Licenses | Select -ExpandProperty ServiceStatus | ?{($_.ProvisioningStatus -eq "Success")}).ServicePlan.ServiceName        
        If (($EnabledFeature -ne $null) -and ($EnabledFeature.GetType().BaseType.Name -eq "Array")){                       
            $EnabledFeature = [string]::Join(',',$EnabledFeature)        
        }
        
        #Getting user license disabled features        
        $DisabledFeature = ($u.Licenses | Select -ExpandProperty ServiceStatus | ?{($_.ProvisioningStatus -eq "Disabled")}).ServicePlan.ServiceName        
        If (($DisabledFeature -ne $null) -and ($DisabledFeature.GetType().BaseType.Name -eq "Array")){                 
            $DisabledFeature = [string]::Join(',',$DisabledFeature)        
        }

        #Updating users Licenses config table       
        $u | Add-Member -MemberType NoteProperty -Name EnabledFeature -Value $EnabledFeature -Force        
        $u | Add-Member -MemberType NoteProperty -Name DisabledFeature -Value $DisabledFeature -Force        
        $u | Add-Member -MemberType NoteProperty -Name O365Licenses -Value $O365Licenses -Force                 
        $Us += $u

    }

    #Exporting user License config    
    $Us | Select userPrincipalName, O365Licenses, EnabledFeature, DisabledFeature | Export-Csv UserLicensesConfig.csv -NoTypeInformation -Delimiter ";" -Encoding UTF8
}

koaf365 : is the company name that I provided when I enrolled in Office 365, and is unique for my organization.

When you run the script :

> Export-UsersLicensesConfig

The generated UserLicensesConfig.csv file content should be like below.

UserPrincipalName O365Licenses EnabledFeature DisabledFeature
user1@agbo.blog E1 BPOS_S_TODO_1, FORMS_PLAN_E1, STREAM_O365_E1, Deskless, FLOW_O365_P1, POWERAPPS_O365_P1, TEAMS1, SHAREPOINTWAC, PROJECTWORKMANAGEMENT, SWAY, MCOSTANDARD, SHAREPOINTSTANDARD, EXCHANGE_S_STANDARD YAMMER_ENTERPRISE
user2@agbo.blog OneDrive For Business Plan 1 FORMS_PLAN_E1,SWAY,SHAREPOINTWAC,ONEDRIVESTANDARD
user3@agbo.blog E1,OneDrive For Business Plan 1 BPOS_S_TODO_1, STREAM_O365_E1, Deskless, FLOW_O365_P1, POWERAPPS_O365_P1, TEAMS1,PROJECTWORKMANAGEMENT,YAMMER_ENTERPRISE, MCOSTANDARD, SHAREPOINTSTANDARD, EXCHANGE_S_STANDARD, FORMS_PLAN_E1, SWAY, SHAREPOINTWAC, ONEDRIVESTANDARD FORMS_PLAN_E1, SHAREPOINTWAC, SWAY
user4@agbo.blog E1,Microsoft Business Center BPOS_S_TODO_1, STREAM_O365_E1, Deskless, FLOW_O365_P1, POWERAPPS_O365_P1, TEAMS1, PROJECTWORKMANAGEMENT, YAMMER_ENTERPRISE, MCOSTANDARD, SHAREPOINTSTANDARD, EXCHANGE_S_STANDARD, MICROSOFT_BUSINESS_CENTER FORMS_PLAN_E1, SHAREPOINTWAC, SWAY
user5@agbo.blog OneDrive For Business Plan 1 FORMS_PLAN_E1,  SWAY, SHAREPOINTWAC, ONEDRIVESTANDARD

 

There you go 🙂 !!!

Installer des Machines Virtuelles à l’aide d’Azure PowerShell

Objectif du lab: Déployer des machines virtuelles à l’aide de PowerShell pour Azure. Nous essayerons de mettre en place l’architecture ci-dessus.

Etape 1 : Créer votre compte azure gratuitement

Je vous invite à utiliser ce tuto pour créer votre compte azure.

Etape 2 : Connectez-vous à votre tenant Azure à l’aide d’Azure PowerShell

Si vous n’avez pas encore installé Azure PowerShell, visiter ce lien sinon lancer PowerShell depuis votre poste de travail (je préfère utiliser PowerShell ISE)

ISE01

 

Saisir la commande suivante pour vous connecter

ISE02

Entrer les informations d’authentifications à votre compte

ISE03

Une fois la connexion réussie, les informations de votre tenant s’affichent en dessous

ISE04

Vous voilà maintenant prêt pour la mise en place du lab 🙂 !

Etape 3 : Définition des variables pour le déploiement des serveurs

#################### Définition des variables ################
#Les variables du script
$SubscriptionName = "moncompteazure" #Nom de votre tenant Azure
$StorageAccountName = "strgaccnt0508" #Nom de votre compte de stockage qui contiendra les composants Azure que nous allons déployer
$ResourceGroupName = "rscgrp0508" #Regroupe toutes les ressources/composants de notre lab (VMs, NICs, IPs...)
$Location = "West Europe" #Emplacement géographique de notre tenant Azure
$SkuName = "Standard_LRS"
$vms = @("WAP01azlab0408","WAP02azlab0408","ADFS01azlab0408","ADFS02azlab0408") #Les noms de nos VMs
$VMSize = "Standard_A1" #Taille de la VM
$PublisherName = "MicrosoftWindowsServer"
$Offer = "WindowsServer" #Type de VMs
$Skus = "2016-Datacenter" #Système d'exploitation
$Version = "latest"

$nicIndex = 1
$intNicId = -1

#Network name
$vnetName = "az_demolab_network"

#Subnets Names
$int = "INT"
$lan = "LAN"
$subnets = @("int","lan")

#Subnets Address Prefixes
$vnet_Addr_Prefix = "10.10.0.0/16"
$int_Addr_Prefix = "10.10.1.0/24"
$lan_Addr_Prefix = "10.10.2.0/24"

#Internet IP addresses
$wap_intIpName = @("","")

##WAP Network config
#NIC config
$nic_Lan_WAP01 = "nic_Lan_WAP01"
$nic_Lan_WAP02 = "nic_Lan_WAP02"
$nic_int_WAP01 = "nic_int_WAP01"
$nic_int_WAP02 = "nic_int_WAP02"

#lan 10.10.2.1x
$lan_ip_WAP01 = "10.10.2.11"
$lan_ip_WAP02 = "10.10.2.12"

##FS Network Config
#NICs
$nic_Lan_FS01 = "nic_Lan_FS01"
$nic_Lan_FS02 = "nic_Lan_FS02"

#lan 10.10.2.2x
$lan_ip_FS01 = "10.10.2.21"
$lan_ip_FS02 = "10.10.2.22"

#Network security groups
$networkSecurityGroupName = "az_demolab$(Get-Random)"
$NetworkSecurityRuleConfig_RDP = "az_demolab_NSRCfg_RDP"
$NetworkSecurityRuleConfig_HTTP = "az_demolab_NSRCfg_HTTP"
[int]$DestinationPortRange_RDP = 3389
[int]$DestinationPortRange_HTTP = 80

Etape 4 : Configuration des composants réseaux

############################# Network Config ###########################
#Creating Resource group
New-AzureRmResourceGroup -Name $ResourceGroupName -Location $Location

#Creating Resource storage
New-AzureRmStorageAccount -ResourceGroupName $ResourceGroupName -Name $StorageAccountName -Location $Location -SkuName $SkuName

#Create two virtual subnets INT and LAN
$subnet_int_Addr_Pr = New-AzureRmVirtualNetworkSubnetConfig -Name $int -AddressPrefix $int_Addr_Prefix
$subnet_lan_Addr_Pr = New-AzureRmVirtualNetworkSubnetConfig -Name $lan -AddressPrefix $lan_Addr_Prefix

#Create virtual Networks
$vnet = New-AzureRmVirtualNetwork -ResourceGroupName $ResourceGroupName -Name $vnetName -AddressPrefix $vnet_Addr_Prefix -Location $Location -Subnet $subnet_int_Addr_Pr,$subnet_lan_Addr_Pr

#Create virtual public ips for the WAP Servers
$i = 0 
Do { $wap_intIpName[$i] = New-AzureRmPublicIpAddress -ResourceGroupName $ResourceGroupName -Location $Location -AllocationMethod Dynamic -IdleTimeoutInMinutes 4 -Name ("wap0" + ($i+1) + "_intIp")
 $i +=1
}
While ($i -lt 2)

Etape 5 : Création des groupes de sécurité

###################### Network Security Groups config ####################
# Create an inbound network security group rule for port 3389
$SecurityRulesRDP = New-AzureRmNetworkSecurityRuleConfig -Name $NetworkSecurityRuleConfig_RDP -Protocol Tcp -Direction Inbound -Priority 1000 -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange $DestinationPortRange_RDP -Access Allow

# Create an inbound network security group rule for port 80
$SecurityRulesHTTP = New-AzureRmNetworkSecurityRuleConfig -Name $NetworkSecurityRuleConfig_HTTP -Protocol Tcp -Direction Inbound -Priority 1001 -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange $DestinationPortRange_HTTP -Access Allow

# Create a network security group
$NetworkSecurityGroup = New-AzureRmNetworkSecurityGroup -ResourceGroupName $ResourceGroupName -Location $Location -Name $networkSecurityGroupName -SecurityRules $SecurityRulesRDP,$SecurityRulesHTTP

Etape 6: Création des Machines Virtuelles

#################### Creating NICs and VMs #########################
#Récupération des informations d'authentification du compte admin local des VMs
$cred = Get-Credential

ForEach ($vm in $vms) {
#Création des interfaces réseaux lan pour les WAP et les FS
 $lanNic = New-AzureRmNetworkInterface -Name ($vm + "_lanNic" + $nicIndex) -ResourceGroupName $ResourceGroupName -Location $Location -SubnetId $vnet.Subnets[1].Id -NetworkSecurityGroupId $NetworkSecurityGroup.Id

#Configuration des VMs WAP
 if ($vm -ilike "WAP*"){
 $intNicId += 1

 #Création des interfaces réseaux internet pour les WAP
 $intNic = New-AzureRmNetworkInterface -Name ($vm + "_intNic" + $nicIndex) -ResourceGroupName $ResourceGroupName -Location $Location -PublicIpAddressId $wap_intIpName[$intNicId].Id -SubnetId $vnet.Subnets[0].Id -NetworkSecurityGroupId $NetworkSecurityGroup.Id 
 $vmConfig = New-AzureRmVMConfig -VMName $vm -VMSize $VMSize | Set-AzureRmVMOperatingSystem -Windows -ComputerName $vm -Credential $cred | Set-AzureRmVMSourceImage -PublisherName $PublisherName -Offer $Offer -Skus $Skus -Version $Version | Add-AzureRmVMNetworkInterface -Id $intNic.Id -Primary $vmconfig = $vmConfig | Add-AzureRmVMNetworkInterface -Id $lanNic.Id
}

#Configuration des VMs FS
 else {
  $vmConfig = New-AzureRmVMConfig -VMName $vm -VMSize $VMSize | Set-AzureRmVMOperatingSystem -Windows -ComputerName $vm -Credential $cred | Set-AzureRmVMSourceImage -PublisherName $PublisherName -Offer $Offer -Skus $Skus -Version $Version | Add-AzureRmVMNetworkInterface -Id $lanNic.Id
 }
 
 #Création de la Machine Virtuelle
 New-AzureRmVM -ResourceGroupName $ResourceGroupName -Location $Location -VM $vmConfig
}

…Ps: vous pouvez exécuter toutes ces étapes en une seule fois en collant les bouts de script les uns à la suite des autres 🙂

Etape 7 : Vérification du bon déploiement des serveurs et de leurs composants

#Le groupe de ressources

02

#Les Machines virtuelles créées

01

#Les composants réseaux

03

ISE05

Nous sommes à la fin de notre déploiement… 🙂

Installer le module PowerShell pour Azure

Hello 🙂 , retrouvez dans ce post comment installer le Module Azure For PowerShell afin de pouvoir gérer vos machines virtuelles Azure à distance à l’aide de cmdlets.

Tout d’abord, il est important de savoir qu’il y a deux types de machines virtuelles dans Azure:

  • Les Machines virtuelles classiques
  • Les Machines virtuelles gérées (Remote Managed VM)

Pour installer les modules de gestions de machines virtuelles, suivre la procédure ci-dessous. Votre ordinateur doit être connecté à l’internet pour que les téléchargements se fassent automatiquement.

Ouvrir une console PowerShell,

Install-Module AzureRM # Pour les Machines virtuelles gérées
Install-Module Azure # Pour les Machines virtuelles classiques

Si vous procédez à l’installation depuis PowerShell ISE, vous observerez la progression comme ci-dessous:

Azure2

L’installation terminée, utiliser la commande ci-dessous pour vérifier la présence du module Azure.

Get-Module -ListAvailable *Azure*

Azure3

Et voilà 🙂 … Vous êtes presque prêt pour gérer vos machines virtuelles.

Dans le prochain post, je vous montrerai comment vous connecter à Azure et Créer un environnement de test.