Office 365: How to add users and licenses through PowerShell!

This time I would like to share a new PowerShell script that shows how to add new Office 365 users and also their licenses reading all the users and licenses information from a CSV file that follows the format bellow:

image_thumb[1]

As you can see, the .csv file simply contains for each user the minimum information required to create a new user in Office 365 (User Principal Name and User Display Name) and the Office 365 license information that will be used later on to configure properly the licenses we need to add to each user. For instance, to disable Office, Yammer and Azure RMS services for each user, we have to include license information in the following way: "OFFICESUBSCRIPTION,YAMMER_ENTERPRISE,RMS_S_ENTERPRISE".The PowerShell Script that allows to create new users and licenses to them is the following one:

   1: ############################################################################################################################################

   2: # Script that allows to do a add users to Office 365 in bulk. The users are read from a CSV file. 

   3: # The csv file only needs a column that stores the account principal name for each user to be added to Office 365

   4: # Required Parameters:

   5: #  -> $sUserName: User Name to connect to the SharePoint Admin Center.

   6: #  -> $sMessage: Message to show in the user credentials prompt.

   7: #  -> $sInputFile: Message to show in the user credentials prompt.

   8: ############################################################################################################################################

   9:  

  10: $host.Runspace.ThreadOptions = "ReuseThread"

  11:  

  12: #Definition of the function that allows to add to Office 365 the list of users contained in the CSV file.

  13: function Add-Office365Users

  14: {

  15:     param ($sInputFile)

  16:     try

  17:     {   

  18:         # Reading the Users CSV file

  19:         $bFileExists = (Test-Path $sInputFile -PathType Leaf) 

  20:         if ($bFileExists) { 

  21:             "Loading $sInputFile for processing..." 

  22:             $tblUsers = Import-CSV $sInputFile            

  23:         } else { 

  24:             Write-Host "$sInputFile file not found. Stopping the import process!" -foregroundcolor Red

  25:             exit 

  26:         }         

  27:         

  28:         # Deleting the users

  29:         Write-Host "Adding the Office 365 users ..." -foregroundcolor Green    

  30:         foreach ($user in $tblUsers) 

  31:         { 

  32:             "Adding user " + $user.UserPrincipalName.ToString()            

  33:             New-MsolUser -UserPrincipalName $user.UserPrincipalName -DisplayName $user.UserDisplayName

  34:         } 

  35:  

  36:         Write-Host "-----------------------------------------------------------"  -foregroundcolor Green

  37:         Write-Host "All the users have been added. The processs is completed." -foregroundcolor Green

  38:         Write-Host "-----------------------------------------------------------"  -foregroundcolor Green

  39:     }

  40:     catch [System.Exception]

  41:     {

  42:         write-host -f red $_.Exception.ToString()   

  43:     } 

  44: }

  45:  

  46: #Definition of the function that allows to assign Office 365 licenses to the specific users read from a CSV file.

  47: function Add-Office365LicensesToUsers

  48: {

  49:     param ($sInputFile,$sOperationType)

  50:     try

  51:     {   

  52:         # Reading the Users CSV file

  53:         $bFileExists = (Test-Path $sInputFile -PathType Leaf) 

  54:         if ($bFileExists) { 

  55:             "Loading $sInputFile for processing..." 

  56:             $tblUsers = Import-CSV $sInputFile            

  57:         } else { 

  58:             Write-Host "$sInputFile file not found. Stopping the import process!" -foregroundcolor Red

  59:             exit 

  60:         } 

  61:         

  62:         # Deleting the users

  63:         $msolAccountSKU=Get-MsolAccountSku        

  64:         Write-Host "Adding the Office 365 licenses ..." -foregroundcolor Green    

  65:         foreach ($user in $tblUsers) 

  66:         {    

  67:             Write-Host "--------------------------------------------------------"

  68:             Write-Host "Adding license $msolAccountSKU.AccountSkuId to the user " $user.UserPrincipalName.ToString()

  69:             Write-Host "--------------------------------------------------------"    

  70:             #Setting the location for the user

  71:             Set-MsolUser -UserPrincipalName $user.UserPrincipalName -UsageLocation "ES"

  72:             switch ($sOperationType) 

  73:                 { 

  74:                 "Remove" {

  75:                     #Remove complete SKU

  76:                     Set-MsolUserLicense -UserPrincipalName $user.UserPrincipalName -RemoveLicenses $msolAccountSKU.AccountSkuId

  77:                     }

  78:                 "Add" {

  79:                     #Add complete SKU      

  80:                     Set-MsolUserLicense -UserPrincipalName $user.UserPrincipalName -AddLicenses $msolAccountSKU.AccountSkuId 

  81:                     }

  82:                 "CustomAdd" {

  83:                     #Custom license assignment                                    

  84:                     $msolLicenseOptions = New-MsolLicenseOptions -AccountSkuId $msolAccountSKU.AccountSkuId -DisabledPlans $user.ServicePlan                         

  85:                     Set-MsolUserLicense -UserPrincipalName $user.UserPrincipalName -LicenseOptions $msolLicenseOptions

  86:                     }                    

  87:                 default {

  88:                         Write-Host "Requested Operation not valid!!" -ForegroundColor Green          

  89:                     }

  90:                 }

  91:             #Reading the licenses available for the user

  92:             (Get-MsolUser -UserPrincipalName $user.UserPrincipalName).Licenses.ServiceStatus

  93:                        

  94:         } 

  95:  

  96:         Write-Host "-----------------------------------------------------------"  -foregroundcolor Green

  97:         Write-Host "All the licenses have been assigned. The processs is completed." -foregroundcolor Green

  98:         Write-Host "-----------------------------------------------------------"  -foregroundcolor Green

  99:     }

 100:     catch [System.Exception]

 101:     {

 102:         write-host -f red $_.Exception.ToString()   

 103:     } 

 104: }

 105:  

 106: #Connection to Office 365

 107: $sUserName="<Your_Office365_Admin_Account>"

 108: $sMessage="Introduce your Office 365 Credentials"

 109: #Connection to Office 365

 110: $msolcred = get-credential -UserName $sUserName -Message $sMessage

 111: connect-msolservice -credential $msolcred

 112:  

 113: $ScriptDir = Split-Path -parent $MyInvocation.MyCommand.Path

 114: $sInputFile=$ScriptDir+ "\PS_UsersToAddOffice365.csv"

 115:  

 116: #Adding Users

 117: Add-Office365Users -sInputFile $sInputFile

 118:  

 119: #Adding Licenses to each user

 120: Add-Office365LicensesToUsers -sInputFile $sInputFile -sOperationType "Remove"

 121: Add-Office365LicensesToUsers -sInputFile $sInputFile -sOperationType "Add"

 122: Add-Office365LicensesToUsers -sInputFile $sInputFile -sOperationType "CustomAdd"

First, we create the new Office 365 users using the New-MsolUser cmdlet and them we add the licenses to them. In order to add the licenses, we need to obtain the current Office subscription using the Get-MsolAccountSku cmdlet and once it is got the license is added to each user using the Set-MsolUserLicense cmdlet. And this is the result we obtain after executing the script:

image_thumb

You can download the PowerShell sript from: How to add new users and asign licenses to them from a CSV file!

References

Office 365: Como añadir usuarios y licencias por medio de PowerShell!

En esta ocasión os dejo un nuevo script que demuestra como añadir nuevos usuarios de Office 365 y licencias leyendo la información de los usuarios y licencias de un archivo CSV que tenga el siguiente formato:

image

Como veis, el archivo .csv simplemente contiene la información relativa al usuario a añadir, el nombre para mostrar del mismo y aquellos servicios de Office 365 que vamos a configurar (en este caso a deshabilitar). Por ejemplo, para deshabilitar Office, Yammer y Azure RMS para un usuario necesitaríamos especificar los planes a deshabilitar de la siguiente forma: "OFFICESUBSCRIPTION,YAMMER_ENTERPRISE,RMS_S_ENTERPRISE".

El script PowerShell que permite añadir los usuarios y las licencias es el siguiente:

   1: ############################################################################################################################################

   2: # Script that allows to do a add users to Office 365 in bulk. The users are read from a CSV file. 

   3: # The csv file only needs a column that stores the account principal name for each user to be added to Office 365

   4: # Required Parameters:

   5: #  -> $sUserName: User Name to connect to the SharePoint Admin Center.

   6: #  -> $sMessage: Message to show in the user credentials prompt.

   7: #  -> $sInputFile: Message to show in the user credentials prompt.

   8: ############################################################################################################################################

   9:  

  10: $host.Runspace.ThreadOptions = "ReuseThread"

  11:  

  12: #Definition of the function that allows to add to Office 365 the list of users contained in the CSV file.

  13: function Add-Office365Users

  14: {

  15:     param ($sInputFile)

  16:     try

  17:     {   

  18:         # Reading the Users CSV file

  19:         $bFileExists = (Test-Path $sInputFile -PathType Leaf) 

  20:         if ($bFileExists) { 

  21:             "Loading $sInputFile for processing..." 

  22:             $tblUsers = Import-CSV $sInputFile            

  23:         } else { 

  24:             Write-Host "$sInputFile file not found. Stopping the import process!" -foregroundcolor Red

  25:             exit 

  26:         }         

  27:         

  28:         # Deleting the users

  29:         Write-Host "Adding the Office 365 users ..." -foregroundcolor Green    

  30:         foreach ($user in $tblUsers) 

  31:         { 

  32:             "Adding user " + $user.UserPrincipalName.ToString()            

  33:             New-MsolUser -UserPrincipalName $user.UserPrincipalName -DisplayName $user.UserDisplayName

  34:         } 

  35:  

  36:         Write-Host "-----------------------------------------------------------"  -foregroundcolor Green

  37:         Write-Host "All the users have been added. The processs is completed." -foregroundcolor Green

  38:         Write-Host "-----------------------------------------------------------"  -foregroundcolor Green

  39:     }

  40:     catch [System.Exception]

  41:     {

  42:         write-host -f red $_.Exception.ToString()   

  43:     } 

  44: }

  45:  

  46: #Definition of the function that allows to assign Office 365 licenses to the specific users read from a CSV file.

  47: function Add-Office365LicensesToUsers

  48: {

  49:     param ($sInputFile,$sOperationType)

  50:     try

  51:     {   

  52:         # Reading the Users CSV file

  53:         $bFileExists = (Test-Path $sInputFile -PathType Leaf) 

  54:         if ($bFileExists) { 

  55:             "Loading $sInputFile for processing..." 

  56:             $tblUsers = Import-CSV $sInputFile            

  57:         } else { 

  58:             Write-Host "$sInputFile file not found. Stopping the import process!" -foregroundcolor Red

  59:             exit 

  60:         } 

  61:         

  62:         # Deleting the users

  63:         $msolAccountSKU=Get-MsolAccountSku        

  64:         Write-Host "Adding the Office 365 licenses ..." -foregroundcolor Green    

  65:         foreach ($user in $tblUsers) 

  66:         {    

  67:             Write-Host "--------------------------------------------------------"

  68:             Write-Host "Adding license $msolAccountSKU.AccountSkuId to the user " $user.UserPrincipalName.ToString()

  69:             Write-Host "--------------------------------------------------------"    

  70:             #Setting the location for the user

  71:             Set-MsolUser -UserPrincipalName $user.UserPrincipalName -UsageLocation "ES"

  72:             switch ($sOperationType) 

  73:                 { 

  74:                 "Remove" {

  75:                     #Remove complete SKU

  76:                     Set-MsolUserLicense -UserPrincipalName $user.UserPrincipalName -RemoveLicenses $msolAccountSKU.AccountSkuId

  77:                     }

  78:                 "Add" {

  79:                     #Add complete SKU      

  80:                     Set-MsolUserLicense -UserPrincipalName $user.UserPrincipalName -AddLicenses $msolAccountSKU.AccountSkuId 

  81:                     }

  82:                 "CustomAdd" {

  83:                     #Custom license assignment                                    

  84:                     $msolLicenseOptions = New-MsolLicenseOptions -AccountSkuId $msolAccountSKU.AccountSkuId -DisabledPlans $user.ServicePlan                         

  85:                     Set-MsolUserLicense -UserPrincipalName $user.UserPrincipalName -LicenseOptions $msolLicenseOptions

  86:                     }                    

  87:                 default {

  88:                         Write-Host "Requested Operation not valid!!" -ForegroundColor Green          

  89:                     }

  90:                 }

  91:             #Reading the licenses available for the user

  92:             (Get-MsolUser -UserPrincipalName $user.UserPrincipalName).Licenses.ServiceStatus

  93:                        

  94:         } 

  95:  

  96:         Write-Host "-----------------------------------------------------------"  -foregroundcolor Green

  97:         Write-Host "All the licenses have been assigned. The processs is completed." -foregroundcolor Green

  98:         Write-Host "-----------------------------------------------------------"  -foregroundcolor Green

  99:     }

 100:     catch [System.Exception]

 101:     {

 102:         write-host -f red $_.Exception.ToString()   

 103:     } 

 104: }

 105:  

 106: #Connection to Office 365

 107: $sUserName="<Your_Office365_Admin_Account>"

 108: $sMessage="Introduce your Office 365 Credentials"

 109: #Connection to Office 365

 110: $msolcred = get-credential -UserName $sUserName -Message $sMessage

 111: connect-msolservice -credential $msolcred

 112:  

 113: $ScriptDir = Split-Path -parent $MyInvocation.MyCommand.Path

 114: $sInputFile=$ScriptDir+ "\PS_UsersToAddOffice365.csv"

 115:  

 116: #Adding Users

 117: Add-Office365Users -sInputFile $sInputFile

 118:  

 119: #Adding Licenses to each user

 120: Add-Office365LicensesToUsers -sInputFile $sInputFile -sOperationType "Remove"

 121: Add-Office365LicensesToUsers -sInputFile $sInputFile -sOperationType "Add"

 122: Add-Office365LicensesToUsers -sInputFile $sInputFile -sOperationType "CustomAdd"

Cómo se deduce en el script, en primer lugar añadimos los usuarios a Office 365 haciendo uso del comando New-MsolUser y a continuación añadimos las licencias de Office 365. Fijaros que en primer lugar obtengo el tipo de suscripción de Office 365 disponible mediante Get-MsolAccountSku y luego procedo a jugar con las opciones de añadir licencias a los usuarios haciendo uso de Set-MsolUserLicense. Y el resultado que obtenemos tras ejecutar el script es el siguiente:

image

Podéis descargaros el script PowerShell de: How to add new users and asign licenses to them from a CSV file!

Referencias: