Office 365 Powershell Examples

Getting started can be the most difficult.  I went through my Office 365 powershell code and pulled out snippets of the items I wish someone made easily available.  I added version AzureAD 2.0 code.

Prerequisites:

 

Connect to Office 365 via Powershell:

#Version 1.0
Import-Module MSOnline 

#Version 2.0
#Install-Module -Name AzureAD 
Import-Module AzureAD

#Version 1.0
#Connection
$msolcred = get-credential 
connect-msolservice -credential $msolcred 
$username = "TenantAdminUsername@contoso.com"; 
#$secpasswd = ConvertTo-SecureString "NewPassword" -AsPlainText -Force 
#$secpasswd = Get-Content $passwordfile | ConvertTo-SecureString; 
#$msolcred = New-Object System.Management.Automation.PSCredential("username", $secpasswd) 
#Run Some msol code
#no disconnection necessary close the powershell window

#Version 2.0
#Connection
$msolcred = get-credential 
Connect-AzureAD -credential $msolcred 
#Run Some AzureAD Code
#Disconnect
Disconnect-AzureAD

#Connect to SharePoint Online 
Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking 
$webUrl = "https://tenantid-admin.sharepoint.com";
Connect-SPOService -Url $webUrl -Credential $msolcred 

#Run some SharePoint Online Powershell Code

#Disconnect from SharePoint Online 
Disconnect-SPOService; 


#Exchange Online Connection 
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $msolcred -Authentication Basic –AllowRedirection 
Import-PSSession $Session 

#run some powershell code for Exchange Online

#Exit Exchange Online Session 
Remove-PSSession $Session 


#Exchange Local Connection 
$sessionoption = New-PSSessionOption -SkipCNCheck 
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri  -Credential $msolcred -AllowRedirection -SessionOption $sessionoption; 
Import-PSSession $Session 

#run some powershell code for Local Exchange Server

#Exit Local Exchange Session 
Remove-PSSession $Session 

Get Office 365 Licenses:

#Version 1.0
Get-MsolAccountSku | Format-Table -AutoSize > Licenses.txt 

#Version 2.0
Get-AzureADSubscribedSku | Format-Table -AutoSize > Licenses.txt

 

 

Get Service Plans for a License:

#Version 1.0
Get-MsolAccountSku | where {$_.AccountSkuId -eq 'tenandid:STANDARDWOFFPACK_IW_STUDENT'}| Select-Object -ExpandProperty ServiceStatus 

#Version 2.0
(Get-AzureADSubscribedSku | ?{$_.SkuPartNumber -eq "STANDARDWOFFPACK_IW_STUDENT"}).ServicePlan | Select-Object -ExpandProperty ServicePlanName

Get a user:

#Version 1.0
Get-MsolUser -UserPrincipalName john@contoso.com 

#Version 2.0
Get-AzureADUser -ObjectId 'john@contoso.com'

Get Unlicensed Users :

#Version 1.0
Get-MsolUser -All -UnlicensedUsersOnly ; 

#Version 2.0
$filter = 'accountEnabled eq true';
Get-AzureADUser -All $True -Filter $filter | where {$_.AssignedLicenses -eq $null -or $_.AssignedLicenses.Count -eq 0 }

Set User Location (this must be done prior to adding an Office 365 license):

#Version 1.0
Set-MsolUser -UserPrincipalName "user@domain.com" -UsageLocation "US"; 

#Version 2.0
Set-AzureADUser -ObjectId "user@domain.com" -UsageLocation "US"

Assign an Office 365 License to a User:

#Version 1.0
Set-MsolUserLicense -UserPrincipalName $eachuser.UserPrincipalName -AddLicenses "tenandid:STANDARDWOFFPACK_IW_STUDENT"; 

#Version 2.0
#Get a single license and modify the options
$license = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicense
$Sku = Get-AzureADSubscribedSku | ?{$_.SkuPartNumber -eq "STANDARDWOFFPACK_IW_STUDENT"}
$license.SkuId = $Sku.SkuId
#Get a licenses object and add the license we modified earlier
$newLicense = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicenses
$newLicense.AddLicenses += $license;
$newLicense.RemoveLicenses = $null; 
#Assign the licenses object to the user
Set-AzureADUserLicense -ObjectId "user@domain.com" -AssignedLicenses $newLicense

Disable Some Service Plans for an Office 365 License:

#Specify which service plans to disable 
#version 1.0
$myO365Sku2 = New-MsolLicenseOptions -AccountSkuId "tenandid:STANDARDWOFFPACK_IW_STUDENT" -DisabledPlans YAMMER_EDU, MCOSTANDARD; 
#Assign the license 
Set-MsolUserLicense -UserPrincipalName $eachuser.UserPrincipalName -AddLicenses "tenandid:STANDARDWOFFPACK_IW_STUDENT"; 
#this disables the plans specified in the license options 
Set-MsolUserLicense -UserPrincipalName $eachuser.UserPrincipalName -LicenseOptions $myO365Sku2; 

#Version 2.0
#Get a single license and modify the options
$license = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicense
$Sku = Get-AzureADSubscribedSku | ?{$_.SkuPartNumber -eq "STANDARDWOFFPACK_IW_STUDENT"}
$license.SkuId = $Sku.SkuId
$license.DisabledPlans += ($Sku.ServicePlans | ?{$_.ServicePlanName -eq "MCOSTANDARD"}).ServicePlanID
#Get a licenses object and add the license we modified earlier
$newLicense = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicenses
$newLicense.AddLicenses += $license;
$newLicense.RemoveLicenses = $null; 
#Assign the licenses object to the user
Set-AzureADUserLicense -ObjectId "user@domain.com" -AssignedLicenses $newLicense

Change UPN for user caused by a Name Change Example:

#Version 1.0
Set-MsolUserPrincipalName -UserPrincipalName 'oldusername@contoso.com' -NewUserPrincipalName 'newusername@contoso.com'

#Version 2.0 
Set-AzureADUser -ObjectId 'oldusername@contoso.com' -UserPrincipalName 'newusername@contoso.com'

Create Remote Mailbox for Student without ever having created a local mailbox and don’t have to wait for sync to Office 365 prior to enabling (User cannot be moved back to on premise exchange server later.  However, this helps with a chicken and egg problem with enabling users in Office 365 and Exchange Online) :

Enable-MailUser -Identity $username1 -ExternalEmailAddress $remotemailbox; 
Set-ADUser -Identity "$username1" –Replace @{msExchHideFromAddressLists = $true; msExchRecipientDisplayType = "-2147483642"; msExchRecipientTypeDetails = "2147483648"; msExchRemoteRecipientType = "4"}; 
#next step is to mass license all students at the end of the day (licensing the student account with Exchange Online will create a mailbox) 

Set Time Zone for Office 365 Mailbox and Provision:

$Upn = 'test@contoso.com' 
Set-MailboxRegionalConfiguration -identity $Upn –Language en-US -TimeZone "Pacific Standard Time" -DateFormat "M/d/yyyy" -confirm:$False; 
Test-MapiConnectivity $Upn; 

Provision OneDrive/Personal Site for up to 99 users:

Make sure you get the newest version of  SharePoint Online Management Shell https://www.microsoft.com/en-us/download/details.aspx?id=35588 or you could get password re-prompts.

#Connect to SharePoint Online then 
$usersToProvision = @('user1@contoso.com','user2@contoso.com') 
Request-SPOPersonalSite -UserEmails $usersToProvision; 

Test OneDrive Provisioning was Successful:
To test OneDrive provisioning succeeded. Log into Office 365 using a tenant admin account then hit the url below replacing username and tenant information as needed. (Tenant admin OneDrive must already be provisioned as well prior to testing by clicking on OneDrive tile while logged in.)

Error means it was not provisioned, page loads to onedrive means success.

Force All Users in Local Exchange Email Address Policy to be Updated (If properties are modified via powershell this might need to be run):

Update-EmailAddressPolicy -Identity EMAILADDRESSPOLICYNAME

AD Connect Delta Synch:

Import-Module ADSync 
Start-ADSyncSyncCycle -PolicyType Delta 

AD Connect Full Synch (If you add any OU’s or properties to synch then a full synch needs to be run):

Import-Module ADSync 
Start-ADSyncSyncCycle -PolicyType Initial

 

 

Powershell Setup and Office 365 Powershell Setup Resources:
Fix Powershell ISE and powershell to be able to run .net 2.0 and .net 4.0 code and clr version for powershell
# or http://stackoverflow.com/questions/2094694/how-can-i-run-powershell-with-the-net-4-runtime
Azure AD Module (x64): http://go.microsoft.com/fwlink/p/?linkid=236297 or https://msdn.microsoft.com/en-us/library/jj151815.aspx
.NET 4.5.2 or newer
SharePoint Online SDK? install https://www.microsoft.com/en-us/download/details.aspx?id=42038
SharePoint Online Management Shell https://www.microsoft.com/en-us/download/details.aspx?id=35588
Microsoft Online Services Sign-In Assistant https://www.microsoft.com/en-us/download/details.aspx?id=28177
Powershell 3.0 https://www.microsoft.com/en-us/download/details.aspx?id=34595
Make sure one drive for admin account already has onedrive provisioned and licensed for onedrive

Loginto Office 365 as tenant admin
Tile -> Admin -> Admin -> SharePoint -> Settings ->
SharePoint Online Management Shell https://technet.microsoft.com/en-us/library/fp161372.aspx
Turn Scripting capabilities on in Office 365 https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
Office 365 License Information: https://technet.microsoft.com/en-us/library/dn771773.aspx

 

 

You can review some of my previous Office 365 powershell articles on how to loop through users and set options:

http://www.questiondriven.com/category/powershell/

 

Azure Active Directory V2 Resources:

Azure Active Directory V2 PowerShell module

https://docs.microsoft.com/en-us/powershell/azuread/v2/azureactivedirectory

https://docs.microsoft.com/en-us/powershell/azuread/v2/connect-azuread

https://docs.microsoft.com/en-us/powershell/azuread/v2/get-azureaduser

http://blog.enowsoftware.com/solutions-engine/azure-ad-powershell-module

Graph API

https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations#GetUsers

https://msdn.microsoft.com/en-us/library/azure/ad/graph/howto/azure-ad-graph-api-supported-queries-filters-and-paging-options

https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations

4 thoughts on “Office 365 Powershell Examples

  1. Rob de Jong

    Hi,

    I noticed you are using the older MSOnline PowerShell module in your examples. It may be useful to start using the newer Azure Active Directory PowerShell V2 module instead, as we will begin deprecating the MSOnline module when we have migrated the functionality of the MSOnline module to the newer module – currently planned for the Spring of 2017.

    Thanks,

    Rob de Jong

  2. newtopowershell

    Can we sync single user from on Premises active directory to Azure active directory with powershell

    1. Cooper Post author

      If you have AD Connect setup, then you just use powershell to call the differential sync after you have created a new user in AD.

      Import-Module ADSync
      Start-ADSyncSyncCycle -PolicyType Delta

Leave a Reply

%d bloggers like this: