Table of Contents
Regular 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-EXOPowerShellForUsers.ps1
You can download the script from Github.
Click here for the downloadable link.
You need the Exchange Online module which can be found here.
How does the script work?
The script will first get the Organization Management group members to exclude them from the list. You do not want to disable PowerShell for your administrator accounts.
The script has one optional parameter –RolesToExclude. With this Parameter you can add other roles as well. For example when you have helpdesk members that use standard scripts, they’ll need PowerShell as well.
After this it will get all users from the tenant and excludes the role members from the list. After that is done it will disable PowerShell for each user.
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).
can someone post a working version of this
What doesn’t work for you?
I’m not sure if you checked but there are several typos in the script. I managed to get it to run using the below (i commented out the line to disable powershell as i just wanted to test it out):
$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-MsolUser -All
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
}
}