Getting the UPNs of all users in an AD group

If you’re like me, then you might occasionally need to get the UPNs of users in AD groups. The chances are that you’ll go straight to Get-ADGroupMember

However, this function doesn’t return the full AD user object, returning instead a limited amount of information for each user, and that information doesn’t have the UPN in it. Luckily, there’s a quick and easy solution – pass each group member through a normal Get-ADUser function to pull back all of the user details.

Here comes a short script that will export the UPNs to a csv file for you to use in any way that you see fit.

function Get-ADGroupMembers{

	Param(
	    [Parameter(Mandatory)]
	    [string]$group
	)
	
	Get-ADGroupMember $group | 
	Foreach{get-aduser $_.samaccountname} | 
	Select name,userprincipalname,samaccountname |
	Export-csv -path C:\Temp\"$group"_groupmembers.csv -NoTypeInformation

}

Simply set the function up in any way that you like (I have a script that runs when I launch PowerShell which sets up all of my custom functions), and then run Get-ADGroupMembers yourADgroupname and it’ll return the user’s name, UPN, and sAMaccountName. Obviously, modify to suit your needs in relation to what it returns, and where the script outputs it.

I’m sure some people will dislike the function’s name, being extremely close to Get-ADGroupMember, so rename it in your own environment to whatever makes sense to you.

With over 20 years of working in the IT industry, I have a wide experience of many different areas of Information Technology and have specific interests in Cloud Solutions, Windows, Active Directory, and Infrastructure. I'm by no means a coder or programmer, and any snippets I post here work fine in my environment, but I give no assurances to how they may work for you.