Disable PowerShell for users in Exchange by Bas Wijdenes

Yeah, normal users can run PowerShell commands on their own Mailbox.

I recently found out that PowerShell is enabled by default for all users in Exchange Online including the normal user mailbox.

There was a user who had been hacked, and the hacker had placed a forward in the mailbox via PowerShell, but well about this all more in a later blog post.

I still wonder if I should have known that PowerShell is enabled for normal users, though.

From that moment on I immediately thought that this should be disabled for all users in Exchange.


Disable_PowerShell_UserMailboxes.ps1

I assume that most of you only come to this blog post for the script itself, so here is the script and below I continue with the explanation.

I have added the Office 365 admin roles so that PowerShell is not disabled for users with admin rights:

  • Company Administrator
  • SharePoint Service Administrator
  • Exchange Service Administrator
$roles = "Company Administrator", "SharePoint Service Administrator", "Exchange Service Administrator"

$data = @()

foreach ($role in $roles)

{

$r=Get-MsolRole-RoleName $role

write-output$role

$users=Get-MsolRoleMember-RoleObjectId $r.objectid

$data+=$users

}

$users = Get-user -ResultSize unlimited

foreach ($u in $users)

{

if(!($data.emailaddress-contains$u.UserPrincipalName))

{

write-output$u.UserPrincipalName

Set-user-identity $u.UserPrincipalName-RemotePowerShellEnabled $false

}

else

{

Write-host"USER IS IN DATA"-BackgroundColor Red

}

}

How does the script Disable_PowerShell_UserMailboxes.ps1 work?

The script checks whether users have 1 of these 3 roles in Office 365:

  • Company Administrator
  • SharePoint Service Administrator
  • Exchange Service Administrator

After that, all users are retrieved and then checked for each user if they have an admin role, if not PowerShell disabled.

You could add things yourself.
For example, I have added a distribution group where I can enable users for PowerShell.


How to automate this?

Until a year ago I would do this via a Scheduled Task on the management server, but nowadays I use Azure Automation for this.
I’m not going to tell too much about that and more about that here and here (How to).


A little extra

This post contains PowerShell. Would you like to learn the basics better? I have created a new website to learn basic PowerShell in an ’emulator’ environment.
Click here to go learn Basic PowerShell.

Published by

Bas

My name is Bas Wijdenes and I work full-time as a Services Engineer. In my spare time I write about the error messages that I encounter during my work. Furthermore, I am currently occupied with Azure, Office 365, and PowerShell for automating daily tasks.

Leave a Reply

Your email address will not be published. Required fields are marked *