Latest Posts

Showing posts sorted by date for query Microsoft 365. Sort by relevance Show all posts
Showing posts sorted by date for query Microsoft 365. Sort by relevance Show all posts

How to Export Microsoft 365 users to CSV by domains via PowerShell

No comments:

This one is simple, yet something comes my way occasionally. So here's the simplest way of identifying all users using a domains in your Azure AD Tenant / Microsoft 365. 

You can get a report of all users using a domain using the below cmdlets. You will be prompted to specify the domain name when you run. Repeat the script if you have to search multiple domains.

 


 # Find Users by domain (includes search in proxy addresses)

Connect-msolservice

$domainname = read-host "Enter the domain name to get users for"

$domain_users= Get-Msoluser -DomainName $domainname -all| Where-Object { $_.UserPrincipalName -like "*$domainname"}

Write-host "Found $($domain_users.count) users in this domain."

$domain_users | select DisplayName,FirstName,LastName,UsageLocation,UserPrincipalName,Islicensed,@{L = "ProxyAddresses"; E = { $_.ProxyAddresses -join ";"}} | Export-csv .\MSOL_Users.csv -notypeinformation -Append

 

# Find Users by domain (UPN only)

Connect-msolservice

$domainname = read-host "Enter the domain name to get users for"

$domain_users= Get-Msoluser -DomainName $domainname -all| Where-Object { $_.UserPrincipalName -like "*$domainname"}

Write-host "Found $($domain_users.count) users in this domain."

$domain_users | select DisplayName,FirstName,LastName,UsageLocation,UserPrincipalName,Islicensed,@{L = "ProxyAddresses"; E = { $_.ProxyAddresses -join ";"}} | Export-csv .\MSOL_Users-UPN-only.csv -notypeinformation -Append

 

Read More

How to change UPNs in Active Directory and Office 365 in bulk with PowerShell Script

No comments:

What is UserPrincipalName?

The UserPrincipalName attribute value is the Azure AD username for the user accounts.

A UPN consists of a UPN prefix (the user account name) and a UPN suffix (a DNS domain name). The prefix is joined with the suffix using the "@" symbol.

For example, "someone@example.com". A UPN must be unique among all security principal objects within a directory forest.

The UPN is used by Azure AD to allow users to sign-in. The UPN that a user can use, depends on whether the domain has been verified. If the domain has been verified, then a user with that suffix will be allowed to sign-in to Azure AD.

Important:

UPN in Azure AD is unique across the Azure AD Tenant and no two users can have the same UPN.

UPN for the users syncs only once via directory sync process (MIM and Azure AD Connect). Subsequent changes to UPN attribute for any users must be repeated in the Azure AD / Office 365 separately via GUI or PowerShell.

How to find UPNs for users in Office 365?

To get a list of the users with their UPNs, you can connect to Office 365 via PowerShell using M365 admin accounts and run the following cmdlets.

Import-Module MSONLINE

Connect-MSOLSERVICE

Get-msoluser -All | Select-Object DisplayName, FirstName, LastName, UsageLocation, UserPrincipalName, UserType, @{L = "ProxyAddresses"; E = { $_.ProxyAddresses -join ";"}} | Export-Csv -Path E:\Temp\MSOL_Users_25OCT2021.csv -NoTypeInformation


The script generates the following output file ‘E:\Temp\MSOL_Users_25OCT202.csv’. The cmdlets assume ‘E:\Temp\’ directory exists, and the user has ‘write’ access to the location. You can change this path to suit your preferences.

To check a single user, just run one simple cmdlet (after connecting to PowerShell):


Get-msoluser -UserPrincipalName <username> | Select-Object DisplayName, FirstName, LastName, PreferredLanguage, UsageLocation, UserPrincipalName


How to Change UPN for users

Changing UPN for users synced from the local AD is a two-step process. Changes done to UPN in the local AD cannot be synced automatically to the cloud via directory synchronization services like Microsoft Identity Manager or Azure AD Connect.

  1. Change the UPN in the local AD
  2. Change the UPN in the Azure AD

Step 1: Change the UPN in the local AD

Changing UPN in the Local AD is can be done from AD management tools such as Active Directory Administration Center, Active Directory Users and Computers (dsa.msc) or ADSI Edit.

Changing Single user:

To change a single user, update the AD attribute via the GUI tools or PowerShell.



To change multiple uses at once, PowerShell is recommended.

·     Note: Following the change in the local AD, continue to step 2 to make change in the Azure AD too. If the users you are changing are ‘in-cloud’, skip directly to step 2.

Changing multiple users (in bulk): There are multiple methods are doing this in bulk. Two have been included for this guide.

Method 1: By CSV file

1.      Prepare CSV file of users in the below format. Save the file as ‘Change-UPN-AD-Users.csv’. You can use any other file name. Just remember to use it in the next step if you change it.
Example CSV format:

SamAccountName

NewUserprincipalname

sandeep.verma

Sandeep.verma.NEWUPN@domain.com

 

2.  Type the following and hit enter when completed:


Import-Module ActiveDirectory

Import-Csv .\Change-UPN-AD-Users.csv | foreach-object {
Write-host “Changing UPN for user $($_.SamAccountName) to $($_.NewUserPrincipalName)” -Foregroundcolor Cyan

Set-ADUser -identity $_.SamAccountName -userprincipalname $_.Newuserprincipalname }

3.   Verify by GUI or PowerShell.

Import-Csv .\Change-UPN-AD-Users.csv | foreach-object {Get-ADUser -identity $_.SamAccountName | Select SamAccountName, UserPrincipalName

Method 2: By OU

You can also make changes to UPNs at OU level i.e. all users in the OU you select will get changed to a new domain name you specify. For example, all users un the test OU ‘TestOU’ have ‘vermasandeep.local’ as the UPN suffix and need to be changed to the UPN suffix ‘vermasandeep.in’.

1.      Open PowerShell ISE with appropriate admin permissions.

2.      Type the following and hit enter when completed (change $ou and $server as your OU and Server names):

Import-Module ActiveDirectory

$oldSuffix = "vermasandeep.local"

$newSuffix = "vermasandeep.in"

$ou = "OU = TestOU, DC=VERMASANDEEP, DC=local"

$server = "DCM1"

Get-ADUser -SearchBase $ou -filter * | ForEach-Object {

$newUpn = $_.UserPrincipalName.Replace($oldSuffix,$newSuffix)

$_ | Set-ADUser -server $server -UserPrincipalName $newUpn

}

Note: $oldSuffix represents the old domain UPN suffix. $newSuffix represents the new UPN suffix. $ou represents the search path in which and IT professional can use a specific OU or an entire domain.

3.      Verify by GUI or PowerShell.

$ou = "OU=TestOU,DC=VERMASANDEEP,DC=local"

Get-ADUser -SearchBase $ou -filter * | Select SamAccountName, UserPrincipalName

 

 Step 2: Change the UPN in the Azure AD

To change a single user’s UPN in the Azure AD, you can use the following cmdet.

Import-Module MSONLINE

Connect-MSOLSERVICE

Set-MsolUserPrincipalName -UserPrincipalName <Current UPN> -NewUserPrincipalName <New UPN>

For bulk changes, below mentioned PowerShell script is recommended.

1.      Prepare CSV file of users in the below format. Save the file as ‘Change-UPN-AzureAD-Users.csv’. You can use any other file name. Just remember to use it in the next step if you change it.
Example CSV format:

SamAccountName

NewUserprincipalName

sandeep.verma

Sandeep.verma.NEWUPN@domain.com

 

2.     Type the following and hit enter when completed:

        Import-Module MSONLINE

 Connect-MSOLSERVICE

 Import-Csv .\Change-UPN-AzureAD-Users.csv | foreach-object {

Write-host “Changing UPN for user $($_.UserPrincipalName) to $($_.NewUserPrincipalName)” -Foregroundcolor Cyan

Set-MsolUserPrincipalName -UserPrincipalName $_.UserPrincipalName -NewUserPrincipalName $_.NewUserPrincipalName }

3. Verify by GUI or PowerShell.

Import-Csv .\Change-UPN-AD-Users.csv | foreach-object {Get-ADUser -identity $_.SamAccountName | Select SamAccountName, UserPrincipalName

 

Note:

If you try changing the UPN from a managed domain to a federated domain, the following error will appear.


Set-MsolUserPrincipalName : You must provide a required property: Parameter name: FederatedUser.SourceAnchor

If you have such a scenario, leave a comment for help.

Checking results

Once the script above has been run successfully, use the following PowerShell cmdlets to check the new UPNs.

Import-Module MSONLINE

Connect-MSOLSERVICE

Get-msoluser -All | Select-Object DisplayName, FirstName, LastName, UsageLocation, UserPrincipalName, UserType, @{L = "ProxyAddresses"; E = { $_.ProxyAddresses -join ";"}} | Export-Csv -Path E:\Temp\MSOL_Users_25OCT2021.csv -NoTypeInformation

 




Read More

Common issues with PowerShell while installing modules like MSONLINE, AzureAD | PowerShell Install-Module:The term ‘Install-Module’ is not recognized

No comments:
You want to connect to Microsoft 365 tenant with PowerShell to do some bulk operations like assigning licenses to users in bulk, change user properties, or just a simple password reset. You are about to begin your magic by installing your first PowerShell module and face this error  - not a good start, Duh!

PowerShell Install-Module:The term ‘Install-Module’ is not recognized as the name of a cmdlet, function, script file,or operable program.

Check the spelling of the name, or if a path was included,verify that the path is correct and try again.
At line:1 char :1
+Install-module msonline



You try to force the Install-Module cmdlet with -Force switch but meet another error. 😔

Install-Module MSONLINE -Force




What's missing? Why can't you install the PowerShell module?

Most likely, at least one out of below four is missing on your computer - 
  1. PowerShell Version
  2. TLS 1.2
  3. NuGet Provider Package
  4. PSGallery Repository 
Lets see them one by one. 

1. PowerShell Version

To install the powershell modules using install-module cmdlet, you need to run PowerShell 5.1 or higher. 

You can check the current version by simply typing HOST in the PowerShell console:

Get-Host



If the above cmdlet returns version lower than 5.1, you must install Windows Management Framework 5.1. 

To solve this - you can download it from Microsoft site here. 


2. TLS 1.2

Without TLS 1.2, you can't successfully Install NuGet Package Provider which is a prerequisite for installing new PowerShell Modules on a system.

You can check if your PowerShell has support for TLS 1.2 by running:


If you don't see the 'TLS12' in the list, you can enable it for the current PowerShell Session or permanently.

Enable TLS 1.2 in current session only - 

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12


Enable TLS 1.2 permanently- 

# Open Powershell (As Admin)
# Run the following cmdlets to set .NET Framework strong cryptography registry keys:

# Set strong cryptography on 64 bit .Net Framework (version 4 and above)
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord

# Set strong cryptography on 32 bit .Net Framework (version 4 and above)
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord

Exit

# Open PowerShell again and check the current available TLS versions

[Net.ServicePointManager]::SecurityProtocol

Bonus: 

How can you spot the issue is TLS without running these cmdlets?
By looking at the error, which reads - 

PackageManagement\Install-PackageProvider : No match was found for the specified search criteria for the provider ‘NuGet’. The package provider requires ‘PackageManagement’ and ‘Provider’ tags. Please
check if the specified package has the tags.

3. NuGet Package Provider

Install-PackageProvider cmdlet installs modules available the PowerShell Gallery with the PackageManagement tag. PackageManagement requires to download the NuGet package provider. 

You can check if NuGet is already available on your machine by running:

Get-PackageProvider


If NuGet package provider is not installed, install it by running below cmdlet in an elevated PowerShell window:

Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force

4. PSGallery Repository

If the error is due to incorrectly installed or not installed PSRepository, the error may look like:
The error can also look slightly different i.e.

PS C:\WINDOWS\system32> Install-Module -Name MSOnline
PackageManagement\Install-Package : No match was found for the specified search criteria and module name 'MSOnline'.
Try Get-PSRepository to see all available registered module repositories.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.0.0.1\PSModule.psm1:1809 char:21
+ ...          $null = PackageManagement\Install-Package @PSBoundParameters
+                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Microsoft.Power....InstallPackage:InstallPackage) [Install-Package], Ex
   ception
    + FullyQualifiedErrorId : NoMatchFoundForCriteria,Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackage

To solve this - Run the Get-PSRepository cmdlet to confirm the PSGallery PSRepository is installed on the system. 
The output should look like below: 

Get-PSRepository

If not, Restore the default repository by using the command

Register-PSRepository -Default

Bonus: 

How can you spot the issue is PSRepository without running these cmdlets?
By looking at the error, which reads - 

PackageManagement\Install-Package : No match was found for the specified search criteria and module name 'MSOnline'.

The problem is now solved! You can install PowerShell Modules now!

Install-Module MSONLINE -AllowClobber -Force


Enjoy!
Read More