New-MSOLUserPrincipalName

SCENARIO
You’re changing the e-mail domain of a user or even a bunch of users. After that you also need to set their UPN’s to reflect the change.

PROBLEM
The problem is that Azure AD Connect service doesn’t currently support changing domain of a UPN of an object that is already synced! So you have to run a powershell command to change it. But it get’s even more complicated because you can’t change the UPN from one federated domain to another without making it “unfederated” first.

SOLUTION
Enter New-MSOLUserPrincipalName, which is a function that will take the user with the current UPN ($UserPrincipalName), change it to a temporary UPN with the domain extension “@[your tenant].onmicrosoft.com” and change it to the new UPN ($NewUserPrincipalName).

function New-MSOLUserPrincipalName {
  param (
    $UserPrincipalName,
    $NewUserPrincipalName
  )
  $TempUPN = "{0}@[your tenantname].onmicrosoft.com" -f $UserPrincipalName.split("@")
  Set-MsolUserPrincipalName -UserPrincipalName $UserPrincipalName -NewUserPrincipalName $TempUPN | Out-Null
  Set-MsolUserPrincipalName -UserPrincipalName $TempUPN -NewUserPrincipalName $NewUserPrincipalName
  Write-Output -InputObject "Successfully changed UPN from $UserPrincipalName to $NewUserPrincipalName"
}   

Thanx to Johan Dahlbom for this one!

Download PS1 from Dropbox

Download PS1 from Dropbox

Upgrading AD FS 2012R2 to 2016

SCENARIO
You have a working ADFS farm running version 3 on Windows 2012R2 and want to upgrade to ADFS 2016 delivered in Windows Server 2016.

PROBLEM
The problem is that this is, if you ask Microsoft, a very straight forward “next-next-finish” process to do as the only TechNet article I found about it makes it look pretty straight forward. But that article was written for Windows Internal Database (there is now also one for SQL cluster backend. Also you’ll notice at the bottom that it’s written for Technical Preview of Windows Server 2016 and also assumed you have no AD group policies that may break stuff! So there are still alot of things that can, and will, go wrong if you follow that procedure.

SOLUTION
There really isn’t one solution since there are so many issues you may run into but I managed to work through them all. But here are my comments to the TechNet article and where things went wrong for me:
2) It’s never showing in a screenshot but it is shown in the next – you have to chose to join an existing farm, the default option is creating a new farm which is a totally different thing!
But even after going through the setup process succesfully after patching and rebooting I got the error 1297 “A privilege that the service requires to function properly does not exist in the service account configuration. You may use the Services Microsoft Management Console (MMC) snap-in (services.msc) and the Local Security Settings MMC snap-in (secpol.msc) to view the service configuration and the account configuration“. As it turns out, this is a policy issue with the Windows Server 2016 baseline that limits who and what can “Log on as a service” and “Generate a security audit”. Creating an override policy for this and adding the service account running the AD FS service solved this issue for me! (thanks to https://blogs.technet.microsoft.com/pie/2015/09/04/adfs-refuses-to-start-error-1297/)
3) This is actually very important later on knowing which server is primary and not!
4) and 5) These are confirmed as not required if you’re running a SQL cluster backend. However, you still need to check later for which server is primary and not.
6) This entire Powershell is just wrong and not accepted at all, atleast in my environment! You’re much better off starting the Remote Access Manager and starting the Wizard from there. This will allow you to chose the certificate in a dropdown without knowing the thumbprint. But this is where I ran into problems and lot’s of them!

The first problem I had when configuring the WAP was connectivity resulting in the error “An error occurred when attempting to establish a trust relationship with the federation service. Error: Unable to connect to the remote server”. This was first due to physical firewall, then the local firewall policy settings and in the end that the service itself was down! So this was basically alot network issues, not the biggest thing in the world.

Now that that was done with I ran into the next problem that caused so much headache for me – “An error occurred when attempting to establish a trust relationship with the federation service. Error: Unauthorized. Verify that the service account has administrative access on the target Federation Server.”! The account that the WAP uses to connect to the internal AD FS server with that has to be a local user and local admin account on the internal AD FS server (since the WAP server shouldn’t be a member of the same domain as the internal AD FS servers). The problem is that there is a group policy baseline for Windows Server 2016 that denies logon from the network for all local users (“Deny access to this computer from the network“)! This resulted in the error since it wasn’t allowed to login with anything but the console! Setting that to only “Guest” should be enough for this.

So after getting that problem solved I got the next error – “An error occurred when attempting to establish a trust relationship with the federation service. Error: Internal Server Error“. Looking at all logs and events and I couldn’t figure out what tha hell was causing this issue. Well, as it turns out it was related to step 4 and 5 which you shouldn’t have done if you’re running SQL backend! When you point to the internal AD FS service address (the web address sts.xxxxxxx.com) you’re supposed to use a host file to control that and point it to the load balanced IP address. Well when I did that I always ended up on a server that was NOT the primary computer and therefor I couldn’t add the WAP! When I changed the host file to point directly to the IP of a server that was Primary computer for the farm it worked! Just remember to change this back since you don’t want the WAP servers point to one specifik AD FS server.

That is as far as I’ve gotten as the rest of the upgrade involves upgrading the forest and domain schema which I’m really not ready to do.

Remove User Mailbox Permissions

SCENARIO
A user has alot of mailbox permissions to other mailboxes that needs to be revoked.

PROBLEM
The problem is that the GUI, even in an on-prem interface, forces you to remove the permissions on the destination so you have to go to every mailbox he/she has access to, remove the permission and then go to the next. This is very time consuming, one wish you could open the user and remove the permissions to other mailboxes that way, but it doesn’t work like that unfortunately.

SOLUTION
This little script solves this problem. It goes through all mailboxes in your mailenvironment and checks all the boxes that the [USER] has access to and prompts to remove them one by one. I still feel a prompt is necessary because sometimes you get the request to “remove everything except these”, so by prompting we can chose which ones to remove. Alot faster than going to every mailbox in the list! For better performance, I suggest you specify a “-servername EXCHANGESERVER” in the “get-mailbox” command, otherwise it’ll go through the entire Exchange org.

$user = "[USER]"
$permissions = Get-Mailbox -resultsize unlimited | Get-MailboxPermission -User $user
foreach($permission in $permissions)
{
$identity = $permission.identity
$accessright = $permission.accessrights
write-host "Removing permission for $user on $identity"
remove-mailboxpermission -Identity $identity -User $user -Accessrights $accessright
}
Download PS1 from Dropbox

Download PS1 from Dropbox

Change Something On Users From File

SCENARIO
You’re the administrator of an Office 365 tenant and/or on-prem Exchange and Active Directory and you need to make bulk changes to a group of people and you have a list with UPNs ready to use.

PROBLEM
There really is no problem but it may be very repetetive tasks.

SOLUTION
This script will read the file “C:\temp\list_of_upns.txt“, which is just a list of UPN’s, and iterate through them making the change you want. Since I make alot of the same changes to different users depending on what I need. I simply un-comment by removing the “#” for whatever I need to script to change on the user. And remember to put the “#” back in to comment if you want it to do something else or you may end up doing unwanted things on the objects (like converting a bunch of on-prem mailboxes to Room mailboxes, true story!)

# Written by : Kristoffer Strom ([email protected])
# Date: 2017-02-20
#
#Starting the loop
ForEach ($user in $(Get-Content C:\temp\list_of_upns.txt ))
{
write-host $user
#Set-Mailbox $user -Type shared
#$userdn = get-aduser  -Filter{UserPrincipalName -eq $user} -properties DistinguishedName
#$DN = Get-ADUser -Filter { UserPrincipalName -Eq $user }
#set-aduser $DN -Replace @{extensionAttribute1 = "REPLACEMENTTEXT"}
#set-aduser $DN -clear extensionAttribute1, extensionAttribute1, AdminDisplayname, AdminDescription
#remove-adgroupmember -Identity "ADGROUP" -Member $DN
#Set-MsolUserLicense -UserPrincipalName $user -RemoveLicenses "XXXXXXXXXX:ENTERPRISEPACK"
#Set-MsolUserLicense -UserPrincipalName $user -RemoveLicenses "XXXXXXXXXX:POWER_BI_STANDARD"
}
Download PS1 from Dropbox

Download PS1 from Dropbox

Get User Serviceplans

SCENARIO
You’re the administrator of Office 365 and you want to programmatically extract information about what serviceplans (features) a specific user has access to and which he or she doesn’t have access to.

PROBLEM
Microsoft’s way of storing the information regarding licenses and features/plans isn’t quite logical sometimes for unitiated people so this might sound like a very complicated thing to do with Powershell and you’re left to do it through the portal instead.

SOLUTION
This little snippet of code will help you. You can add exporting features to it if you want, or input a user.txt file, but this is the stuff that displays the information. But if you want to get a complete dump of all information for all users, you should use this script instead which does that magic alot better.

#
# Written by : Kristoffer Strom ([email protected])
# Date: 2017-02-20
#
# Here we define what user we're querying:
$upn = "[INSERT UPN HERE]"
# Here we set the index to 0
$i = 0
# Run the query to get user info
$user = get-msoluser -userprincipalname $upn
# Store the license array
$features = $user.licenses
# Just an empty row
write-host ""
# Running the loop to show info on all licenses
while($i -lt $features.count)
{
    $AccountSkuId = $features[$i].AccountSkuId
    Write-host -NoNewline -ForegroundColor Cyan "Features for $AccountSkuId"
    $features[$i].servicestatus | ft
    $i++
}
Download PS1 from Dropbox

Download PS1 from Dropbox

UPDATE: Apparently the new Powershell moduled for MSOL handled this differently so the output became quite different. Rather than type out one plan at a time it bunched them together so there was no way of seeing which feature belonged to which plan. So I re-wrote this with a “while” loop and “format table” command to force it to seperate the output. (seriously, remove the “ | ft” part and see what that does to this snippet!)

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.

Set UsageLocation Where Empty

SCENARIO
You’re the administrator of a large tenant with several different e-mail domains for people in different countries. Manually setting a UsageLocation, which is required for license activation, for them all individually is unrealistic.

PROBLEM
The problem here is we need some way of filtering out who is actually where. The perfect solution is ofcourse to have the AD property (“msExchUsageLocation”) since Azure AD Connect syncs it out of the box. But not everyone has that luxury, especially if it’s a domain you’re not even in charge of. And the get-msoluser cmdlet with -domain filter will not only catch the ones that have the domain as their primary e-mail, but also the ones that have it as secondary so as a filter it won’t work.

SOLUTION
In comes this little bit of code! It loads all users, filters out everyone that has a license and everyone that doesn’t have a UPN matching the domain (in this example “test.se” and for the rest sets the UsageLocation to whatever you want, in this example “SE“. This way, we only get the ones that don’t have a license yet and only the ones with this specific domain as their primary e-mail (which should match UPN). So if your company’s name is “test” and everyone has a “test.com” address as a secondary, but the Swedish employees have “test.se” as their primary you can easily set their usagelocations like this. And then just change it around for the rest of the company.

#
# Written by : Kristoffer Strom ([email protected])
# Date: 2017-02-10
#
# Credit to Reditor bearxor (https://www.reddit.com/user/bearxor)
#
# We check all users for users with no UsageLocation set and matches a e-mail domain (test.se) and sets the UsageLocation SE (=Sweden)
Get-MsolUser -All | where{$_.UsageLocation -eq $null -and $_.userprincipalname -like "*@test.se"} | foreach{set-msoluser -UserPrincipalName $_.UserPrincipalName -UsageLocation "SE"}
Download PS1 from Dropbox

Download PS1 from Dropbox

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

Bulk Converting Domains To Federated

SCENARIO
You’re the administrator of an Exchange environment with lots of domains registered over the years for whatever reasons, as an example different business units with different e-mail domains. You’ve added them all to the Azure AD and verified them but now you need to tie them to the AD Federation Service (ADFS).

PROBLEM
Problem is it takes alot of time to first sort out all domains that are verified and then federating them, a very tedious task.

SOLUTION
Solution is you export all your domains into a CSV file (just listing all the domainnames is fine), the run this script and it will import the CSV file and for every entry it will check to make sure if it’s verified and if so, federate it with the ADFS. Remember to run this on the ADFS server and the Powershell needs to be launched as administrator!

#
# Written by : Kristoffer Strom ([email protected])
# Date: 2017-02-08
#
# Let's begin by importing the file. Change the filename "CSV_FILENAME.csv" to whatever you see fit.
$domains = Import-Csv CSV_FILENAME.csv
# And now we iterate through every entry
foreach ($domain in $domains)
{
  # Getting the status of the domain
  $domainstatus = get-msoldomain -DomainName $domain.DomainName
  # If it's already federated we just say that and move onto the next one
  if($domainstatus.Authentication -eq "Federated") { write-host -Foregroundcolor Yellow "$domain is already federated." }
    # If it's verified we federated it
    ElseIf($domainstatus.Status -eq "Verified") { Convert-MsolDomainToFederated -DomainName $domain.DomainName -SupportMultipleDomain:$true; write-host -Foregroundcolor Green "$domain.DomainName changed to federated" }
    # Or if it's not Verified or doesn't exist we write this error
    ElseIf($domainstatus.Status -ne "Verified") { write-host -Foregroundcolor Red "$domain is not verified or does not exist in tenant." }
}
# End of iteration

OPTIONAL
You could replace the import of the CSV file to read out all the UPN suffixes from your domain. If you’ve done your job for a proper O365 migration you’ve made sure all the UPN’s match their e-mails then all e-mail domains should exist as a UPN suffix. If you want to do that, replace the line “$domains = Import-Csv CSV_FILENAME.csv” with this:

$ADForest = Get-ADForest
$domains = $ADForest.UPNSuffixes

Another option is to do a get-msoldomain and filter on “Verified” domains only. But beware, this will tie all verified domains to your ADFS, be sure you really want that! If you do, replace the “$domains=” statement with this:

$domains = Get-MsolDomain -Status Verified

This script can easily be converted into one that does the initial adding of the domains, but since every domain added gets a vertification code backs doing that in bulk is less than ideal.

Download PS1 from Dropbox

Download PS1 from Dropbox

Powershell to Exchange Online

SCENARIO
You’re used to having your Exchange server in your own environment and Powershelling to it and run all these scripts you’ve collected over the years.

PROBLEM
Now that the mailboxes are in a database you have no control of on a server somewhere at Microsoft how are you supposed to run those Exchange Powershells?

SOLUTION
This is the MS way of executing Powershell against Exchange Online using Powershell commands you’d usually use on an on-premise Exchange environment. This is very basic stuff, but if you’re just getting started with Office 365, this is essential to manage users in Exchange Online!

$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session

Basically what this does is connects you to Exchange Online and starts a remote Powershell session on Microsoft’s server. This unfortunately means that you are limited to the automation limits, which means sometimes when you do really, really heavy stuff you’ll run into throttling errors from “Microsoft.Online.Administration.Automation.MicrosoftOnlineException”. Usually that’s just an error saying you need to code better with more filters!

IT Nerdiness

I’m going to start another blog. I’ve been thinking about it for quite some time but never really got around to doing it. I’m gonna start a boring IT nerdy blog with my own “experiences from the field” from work!
If you didn’t know I’m an IT pro working with SharePoint both in house but also in the cloud, as wel as alot of other “Office 365” things for an enterprise with some 25k users. And one thing that us IT pros do well is share information. I wouldn’t be able to solve half of the issues I’m faced with all the time if it wasn’t for other IT pros out there sharing their experiences and their tricks. And one of the things I think I can contribute with the most is Powershell script.

Nothing too advanced though, just basic powershell tips that other people in my line of work might find usefull so they don’t have to write them their selves. I’m sure some of these scripts can be approved upon, so please let me know if you have suggestions!

Enjoy!