Check if an email address or a UserPrincipalName is already used by an account in your Office 365 tenant

Did you ever need to find in your Office 365 tenant :

  • What object is using a specific email address or UserPrincipalName ?
  • What object is preventing an Active Directory account from syncing because of duplicated email address or UserPrincipalName ?
  • Where are them located in your tenant : in Users, in Contacts or in Deleted users ?

If yes, this article may help you achieve your goal. Find below how to process. To install the Microsoft Online Service Module for Powershell, please follow the instruction in the paragraph Connect with the Microsoft Azure Active Directory Module for Windows PowerShell of this link :

When you are ready, open a Powershell console and Sign in to your Office 365 tenant with an Admin Account using this command line


Run the below Powershell fonction :

function Get-ConflictingAttributes {

  param (

  $SearchTable = @{}
  Write-Host "Searching began :" $(Get-Date) -ForegroundColor Green

  #Searching in all ProxyAddresses
  Write-Host "Searching User and Guest accounts" $(Get-Date) -ForegroundColor Yellow
  $User = Get-MsolUser -All | Where-Object {($_.UserPrincipalName -match $SearchValue) -or ($_.ProxyAddresses -match $SearchValue)}

  #Searching in all deleted users
  Write-Host "Searching Deleted accounts" $(Get-Date) -ForegroundColor Yellow
  $Del = Get-MsolUser -All -ReturnDeletedUsers | Where-Object {($_.UserPrincipalName -match $SearchValue) -or ($_.ProxyAddresses -match $SearchValue)}

  #Searching in contacts
  Write-Host "Searching Contacts" $(Get-Date) -ForegroundColor Yellow
  $Contact = Get-MsolContact -All | Where-Object {$_.EmailAddress -match $SearchValue}

  Write-Host "Searching ended :" $(Get-Date) -ForegroundColor Green

  if ($User){
    $SearchTable.Add($User.UserType,$User) | Out-Null

  if ($Del){
    $SearchTable.Add($Del.UserType,$Del) | Out-Null

  if ($Contact){
    $SearchTable.Add("Contact",$Contact) | Out-Null

  return $SearchTable


Now, suppose that you want to know which account in your Office 365 tenant is using the email address, it’ simple, run this command line in the Powershell console you previously opened :

$Result = Get-ConflictingAttributes -SearchValue ""

To see the result :


We can see that the object using the value “” is a contact and this value is set on his EmailAddress.

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

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 

Get role members

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

RoleMemberType EmailAddress                   DisplayName                        isLicensed
-------------- ------------                   -----------                        ----------
User              user2                      	 True      
User              user3                    		 True      
User              user4                    		 False

Add member to a role

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

Remove member from a Role

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

Check member removal

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

RoleMemberType EmailAddress                   DisplayName                        isLicensed
-------------- ------------                   -----------                        ----------
User              user2                      	 True      
User              user4                    		 False      
User              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à 🙂

Permanently remove a guest user in Office 365

To permanently delete a guest user in your Office 365, follow the steps below.

(1) Check that the account is still active

If your guest user email address is : then his UserPrincipalName is

To check that the guest is still active, use the command lines below

$A =
Get-MsolUser -UserPrincipalName $A


(2) How to delete guest user 

Remove-MsolUser -UserPrincipalName $A


(3) Check that guest user account is present in recycle bin

Get-MsolUser -All -ReturnDeletedUsers | ? {$_.userPrincipalName -eq $A}


(4) How to permanently remove the guest account

Remove-MsolUser -UserPrincipalName $A -RemoveFromRecycleBin


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{

    [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

  $LicenseToAdd = $Null
  $DisableYammer = $False
  $LicenseOptions = @()

  #Finding License Plan to activate
    "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
      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
            Set-MsolUserLicense -UserPrincipalName $User.UserPrincipalName -AddLicenses $LicenseToAdd -LicenseOptions $LicenseOptions -EA SilentlyContinue
            Set-MsolUserLicense -UserPrincipalName $User.UserPrincipalName -AddLicenses $LicenseToAdd
        #Logging inexisting user account
        $User.UserPrincipalName >> $($LogPath + "Upns_Not_Exist.log")
    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 :

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


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 :

Step 2 : Prepare the upns csv file

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


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 {

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

  #License Plans correspondence table
  $LicensePlans = @{
    E1 = "kingo:STANDARDPACK" 
    E3 = "kingo:ENTERPRISEPACK" 

  $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 :


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 :

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.



There you go 🙂 !!!

Rajouter des utilisateurs dans un groupe AD à partir d’un fichier .CSV

Hello, je partage ce petit script qui pourrait vous être utile si vous souhaitez rajouter des utilisateurs (100, 1000…) en bloc à un groupe AD.

Pour  utiliser ce script cela suppose que vous avez déjà la liste de vos utilisateurs et que ces derniers existent déjà dans votre organisation Active Directory. Il faudra donc constituer un fichier .csv et ensuite exécuter le script que je vous fournis dans ce post dans PowerShell sur un contrôleur de domaine.

Le contenu du fichier MesUsers.csv


Le script à utiliser est le suivant:

Import-Module ActiveDirectory #Nous chargeons le module Active Directory 

  $Group = "Nom du Groupe AD" #Group AD dans lequel vous souhaitez rajouter des users 
  $MesUsers = Import-Csv "C:\MesUsers.csv" #Chemin d'accès de votre fichier Csv contenant la liste de vos users 
  $members = Get-ADGroupMember -Identity $Group -Recursive | Select -ExpandProperty Name 

ForEach ($User in $MesUsers){ 

  #Vérifie si l'utilisateur existe déjà dans le groupe  
  If ($members -contains $User.Name){            
    Write-Host "$($User.Name.ToUpper()) exists in the Group" -ForegroundColor Yellow       

  #S'il n'existe pas on le rajoute      
  Elseif (Add-ADGroupMember -Identity $Group -Members $User.Name -ErrorAction SilentlyContinue){            
      Write-Host "$($User.Name.ToUpper()) a été rajouté au group" -ForegroundColor Green      

  #En cas de problème on ressort ici la liste des users qui n'ont pas pu être rajoutés      
     Write-Host "Unable to Add $($User.Name.ToUpper())" -ForegroundColor Red      


Pour visualiser le log des erreurs, histoire de vérifier que le scritp s’est exécuté correctement, il suffit d’afficher le contenu de la variable $error. C’est une variable système pré-définie dans PowerShell.


Et voilà 🙂

Importer une VM Hyper-V dans Microsoft Azure

Dans le précédent article, nous avons vu comment installer Hyper-V sous Windows 10 et créer une VM. Intéressons-nous maintenant à son importation dans Microsoft Azure. Créer un compte de test Microsoft Azure si vous n’en avez pas encore.

Etape 1 : Préparation de la VM Hyper-V pour son importation dans Microsoft Azure

Nous allons syspreper la VM pour que son disque dur puisse nous servir de modèle à la création d’autres machines virtuelles une fois qu’elle est importée dans Azure.

Ouvrons donc une session sur notre VM, puis exécutons l’Outil de préparation sysème qui se trouve dans le répertoire “c:\Windows\System32\Sysprep\”. N’oubliez pas de cliquer sur Généraliser.


Après quelques minutes la VM s’éteint.


Maintenant que notre VM est éteinte, il faut convertir le disque du format VHDX dynamique au format VHD fixe. Ce dernier format est celui supporté par Azure.

Se rendre dans le répertoire où se trouve le disque de la VM et ouvrir une invite de commande PowerShell, et exécuter la commande ci-dessous :

Convert-VHD .\Win10.vhdx -DestinationPath .\Win10.vhd -VHDType Fixed


Etape 2: Importation de la VM dans Azure

Se connecter au tenant Azure dans lequel on souhaite importer la VM à l’aide de la commande Azure PowerShell suivante.


A l’invite d’authentification, entrer le login et mot de passe de votre tenant Azure. Créer un compte de stockage Si vous n’en disposez pas déjà. Utiliser la commande suivante :

New-AzureRmStorageAccount -ResourceGroupName "NomGroupeDeRessource" -Name "NomCompteDeStockage" -Location "west europe" -SkuName "Standard_LRS" -Kind "Storage"


Une fois le compte de stockage créé, nous allons commencer par importer dans un premier temps le disque vhd de notre VM.

$rg = "rscgrp0508"
$Destination =
$LocalFilePath = "C:\Users\jean-marie.agbo\Documents\LAB\Win10.vhd"
Add-AzureRmVhd -ResourceGroupName $rg -Destination $Destination -LocalFilePath $LocalFilePath

On peut observer la progression de l’importation du disque dur.


Le processus d’importation peut nécessiter du temps, alors il faut être patient.


Dans le portail Azure, on voit que le disque de la VM a été bien uploadé.


L’importation de disque terminée, la création de la machine peut maintenant se faire.

#Network name
$vnetName = "az_demolab_network"
$ippubName = "ippub"
$rg = "rscgrp0508"
$ippubName = "ippub"

$Location = "westeurope"
$vnetSubnetCfg = "int"

#Récupération du réseau lan auquel nous souhaitons le rattacher.
$virtualnetwork = Get-AzureRmVirtualNetwork -Name "az_demolab_network" -ResourceGroupName $rg
$subnetId = (Get-AzureRmVirtualNetworkSubnetConfig -Name $vnetSubnetCfg -VirtualNetwork $virtualnetwork).Id

#Mot de passe de l'administrateur local de votre VM
$credential = Get-Credential

#Création de la machine virtuelle dans Azure
$win10pubIp = New-AzureRmPublicIpAddress -Name $ippubName -ResourceGroupName $rg -Location $location -AllocationMethod Dynamic # -IdleTimeoutInMinutes 4

$NetworkInterface = "win10Nic"
$win10Nic = New-AzureRmNetworkInterface -Name $NetworkInterface -ResourceGroupName $rg -Location $Location -SubnetId $subnetId -PublicIpAddressId $

#Nom de stockage de la VM
$StrAccName = "strgaccnt0508"
$StorageAccountName = Get-AzureRmStorageAccount -AccountName $StrAccName -ResourceGroupName $rg

#Créer la configuration de la VM
$VMName = "Win10"
$VMSize = "Standard_A1"
$vmConfig = New-AzureRmVMConfig -VMName $VMName -VMSize $VMSize

$vm = Set-AzureRmVMOperatingSystem -VM $vmConfig -Windows -ComputerName $VMName -Credential $credential -ProvisionVMAgent -EnableAutoUpdate
$vm = Add-AzureRmVMNetworkInterface -VM $vmConfig -Id $win10Nic.Id

#Création du disque système
$osDiskUri = ’{0}vhds/{1}-{2}.vhd’ -f $StorageAccountName.PrimaryEndpoints.Blob.ToString(), $VMName.ToLower(), "OS"

$SourceImageUri = ""
$vm = Set-AzureRmVMOSDisk -VM $vm -Name "win10-SE" -VhdUri $osDiskUri -CreateOption fromImage -SourceImageUri $SourceImageUri -Windows

#Création de la machine virtuelle
New-AzureRmVM -ResourceGroupName $rg -Location $location -VM $vm -Verbose

Dans notre tenant Azure, nous pouvons voir notre VM créée.


Nous avons terminé notre importation.

A très bientôt pour un prochain article. N’hésitez pas à me contacter si vous avez des sujets intéressants sur lesquels on pourrait travailler et faire une publication.

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)



Saisir la commande suivante pour vous connecter


Entrer les informations d’authentifications à votre compte


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


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 = ""
$int_Addr_Prefix = ""
$lan_Addr_Prefix = ""

#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_ip_WAP01 = ""
$lan_ip_WAP02 = ""

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

$lan_ip_FS01 = ""
$lan_ip_FS02 = ""

#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


#Les Machines virtuelles créées


#Les composants réseaux



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