Get AD User By UPN

SCENARIO
You’re managing Office 365 and want to do Powershell quieries against the on-premise Active Directory

PROBLEM
The problem is that Office 365 cmdlets like “get-msoluser” always gives you the users userprincipalname (UPN) because that is all that Office 365 cares about. But when you want to query the local on-premise Active Directory with “get-aduser” it doesn’t recognise the UPN when searching for users.

SOLUTION
The solution is adding it as a filter like this, where $MSOLUPN is the UPN you get from “get-msoluser“:

Get-ADUser -Filter { UserPrincipalName -Eq $MSOLUPN }

Again, this is pretty basic stuff, but still something you need to know and use all the time.

Add Users To Group Based On Attribute

SCENARIO
You have a bunch of users with some property in common in your on-prem AD and you want to add them all to an AD group.

PROBLEM
Normally to add a bunch of users to an AD group you’d simple use “dynamic groups” and set the filter up and never bother with it again. This however becomes a problem when dealing with Azure AD since that doesn’t support dynamic groups (since it can’t look up all properties in your AD).

SOLUTION
The solution is below. You specify the name of the AD group (“NAME_OF_AD_GROUP” in example below) you want to add users, you change what attribute (“extensionattribute1“) you want it to filter on and what the attribute has to be (“WHATEVER“) and the script iterates through every users and adds them to the AD group. This can be setup as a secheduled task to get the same effect as a dynamic group but would work for Azure AD as well.

#
# Written by : Kristoffer Strom ([email protected])
# Date: 2017-02-09
#
# We start by defining what AD group we want to add the users to
$nameofgroup = "NAME_OF_AD_GROUP"
# Then we get a list of users based on an attribute, in this case "Extensionattribute1" equals "WHATEVER"
$listofusers = Get-ADUser -filter {extensionattribute1 -eq "WHATEVER"}
# Now we iterate through every user
foreach($individualuser in $listofusers)
  {
  # We declare this variable for write-host purposes only.
  $UserPN = $individualuser.UserPrincipalName
  # And we can write out the operation while we're at it
  Write-Host "Adding $UserPN to group $nameofgroup."
  # And add them to the group
  Add-ADGroupMember $nameofgroup $individualuser.DistinguishedName
  }
Download PS1 from Dropbox

Download PS1 from Dropbox