Disable PowerShell for users in Exchange by Bas Wijdenes

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.


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).

Published by

Bas Wijdenes

My name is Bas Wijdenes and I work as a PowerShell Automation Engineer. My main focus is PowerShell, Azure AD, Azure Infrastructure, Server Management, and Exchange (Online).

3 thoughts on “Disable PowerShell for users in Exchange by Bas Wijdenes”

  1. 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



    $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




    Write-host “USER IS IN DATA”-BackgroundColor Red



Leave a Reply

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