Category: Computers and Internet

Exchange: How to list memberOf groups of a distribution group?

When I wrote a script to migrate distribution groups to Office 365 from On-Prem Exchange server, I had a requirement to list the parent (memberOf) groups. So I can migrate them in order or do not lose the group memberships during migration.

So how do we list the parent groups of a DL? There are different methods to get the memberOf groups for on-premises or Office 365 environment.


I am using AD cmdlets, because they are very easy use. This command will display the parent (memberof) groups of their Email:

Get-ADGroup <Group Name> -Properties memberOf | Select-Object memberOf | Where-Object { $dn =[string] $_.memberOf ; Get-ADObject $dn -Properties mail | Select-Object mail}

Office 365/Exchange Online

I end up using Exchange Online cmdlets in Exchange online. It may be little slower then On-Prem command. Idea is run Get-Group command with a filter if the group show up in any group’s members. This will list the memberOf groups (of them email address).

$GroupDN = (Get-Group ).distinguishedName
$filter = "Members -eq '$GroupDN'"
(Get-Group -Filter $filter).WindowsEmailAddress


Office 365: How to correct UserPrincipalName for On-premises AD sync’ed account?

Say you end up with a wrong UserPrincipalName for an MSOL account which is sync’ed from On-Prem Active Directory like this:, Which is obviously wrong UPN. The correct UPN supposed to be like and it should match the user’s PrimarySMTPAddress.

I am sure you tried to correct it in Office 365 Admin Center, where UPN is grayed out. You may have tried MSOL PowerShell command Set-MSOLUser which does not have the parameter -UserPrincipalName. Right? That why you are here.

Solution: Easy Peacy. You have to use the another MSOL PowerShell command like this:

-UserPrincipalName -NewUserPrincipalName 

That’s it. You have done it. Have an coffee! You deserve it! 🙂

Active Directory: Send password expiry Email notice to users

Here is very useful script written by me. Feel free to use on your network.

This script queries the local Active Directory for users whose password is expiring in given number of days, then send email notice to the user.

Download the PowerShell Script

The source code:

    ** Script: Email-PasswordExpiry-Notice.ps1                                                      **
    ** Purpose: Send Email Notice to users before their AD passwrod expires                         **
    ** Note: Make sure to provide your own values with the comment "$# <--- "" in this script       **
    **                                                                                              **
    ** Written by: Anand, the Awesome, Venkatachalapathy                                            **

$DaysBeforeExpiry = 5 # <--- Change your own number of days before password expiry (to start SPAMing users)

# Query AD for users whose password is expiring close to $DaysBeforeExpiry days
$users = Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} –Properties "DisplayName", "msDS-UserPasswordExpiryTimeComputed","mail"  `
| Where-Object {$_.mail -ne $null } `
| Select-Object -Property "Displayname",@{Name="ExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}},"Mail","SamAccountName" `
| Where-Object {$_.ExpiryDate -lt (Get-Date).AddDays($DaysBeforeExpiry) -and $_.ExpiryDate -gt (Get-Date) } 

#Send Email to the users from the above query results
$from = ""  # <--- Change your own From Email address
$smtpserver = ""     # <--- Type your local SMTP server

foreach($user in $users)
    $expirydays = (([DateTime]$user.ExpiryDate) - (get-date)).Days
    $to = $user.mail
    $username = $user.SamAccountName
    $domainname = env:USERDOMAIN
    $subject = "Your Password Will Expire in $expirydays Days"

    $body = @"
Your Active Directory account ($domainname\$username) Password Will Expire in $expirydays Days. 

Change your password when possible. On Windows computer, press Control-Alt-Delete & choose change password. 

--Your Friendly Neighbourhood IT 
    '*' * 80
    Send-MailMessage -Body $body -From $from -SmtpServer $smtpserver -Priority High -Subject $subject -To $to 


    ***************** The End of the Script *****************

Active Directory – PowerShell – Cannot search by null value attributes

If you tried to filter results with any AD cmdlets in PowerShell, you quickly finds out it is not possible with “-Filter” option. For example, I tried to list any user with no Mail attribute value is null:

PS E:> Get-ADUser -Filter { mail -ne $null }
 Get-ADUser : Variable: 'null' found in expression: $null is not defined.
 At line:1 char:1
+ Get-ADUser -Filter { mail -ne $null }
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
       + CategoryInfo : InvalidArgument: (:) [Get-ADUser], ArgumentException
       + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUser 

Well, the solution is to use -LDAPFilter instead of -Filter option. Here is the working command:

PS E:> Get-ADUser -LDAPFilter '(!mail=*)' -ResultSetSize 5 -Properties mail | Select-Object Name,Mail
 Name          Mail
 ----          ----
 Josh Doe         

So the trick is ‘(mail=*)’ filter brings all user accounts with mail account has any value. Adding [NOT] operator in front of mail ‘(!mail=*)’ in the LDAPFilter results with all user accounts with mail attribute is empty.

So use the filter string with any AD property to search like this: -LDAPFilter ‘(!mail=*)’

Active Directory: Password Expiry date Report for all accounts

I had a requirement to generate password expiry date report for all accounts to validate a password policy change. Here is what I came up with (who know someone have same need for this report).

Important point is the calculated property msDS-UserPasswordExpiryTimeComputed. Which is in Long Date format.

It will create an CSV file on the same directory on where the script runs.

Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False}  –Properties "DisplayName", "msDS-UserPasswordExpiryTimeComputed"
 | Select-Object -Property "Displayname",@{Name="ExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}} `
 | Export-Csv -path .\Password-Expiry-Report.csv -NoTypeInformation

Here is the same report:

“Tim Dangthatsme”,”8/23/2019 9:23:10 AM”
“Don Anonymous”,”7/31/2014 3:17:20 AM”
“Robert Dome”,”12/17/2019 8:14:17 AM”
“Introvert Hopkins”,”9/6/2019 10:57:07 AM”

Fun: Get Weather information in PowerShell

Found these helpful sites ( and and wrote an script to get and display weather information of your current location. Now in a shell, I can check weather information too. 🙂

 Script: Get-Weather.ps1
 Description: This script will
     * Get current location
     * Find the Weather info
     * Display the weather info

 Fun fact: This command will display the GPS location

 Invoke-RestMethod -URI "" -Method GET | Select  City,Region,Country,loc | FT -auto


#Get current location (city)
$City = (Invoke-RestMethod -URI "" -Method GET).City

#get Weather info
$weather = Invoke-WebRequest -Uri "$City"
$WeatherInfo = $weather.ParsedHtml.body.outerText

#Display the weather info