Script repository

Connect to Exchange with PowerShell

Updated on: Jan 18, 2026, Views: 24485

Exchange

The scripts show how to connect to Exchange from Adaxes with the help of PowerShell. To execute either of the scripts, create a business rule, custom command or scheduled task configured for the required object type.

Exchange Online

try
{
    # Get the object ID in Microsoft 365.
    $objectId = [Guid]$Context.TargetObject.Get("adm-AzureId")
}
catch
{
    return
}

# Connect to Exchange Online.
$Context.CloudServices.ConnectExchangeOnline() 
    
Set-Mailbox $objectId.ToString() -Type Shared # TODO: replace with the code you need to execute

Exchange on-premises

In the script, the $exchangeServer variable specifies the fully-qualified domain name or IP address of the Exchange server.

$exchangeServer = "exchangeServer.domain.com" # TODO: modify me

try
{
    # Connect to Exchange server.
    $session = New-PSSession -connectionURI "http://$exchangeServer/powershell" -ConfigurationName Microsoft.Exchange
    Import-PSSession -session $session -CommandName "Set-Mailbox" -AllowClobber

    Set-Mailbox "%distinguishedName%" -Type Shared # TODO: replace with the code you need to execute
}
finally
{
    # Close the remote session and release resources.
    if ($session) { Remove-PSSession -Session $session}
}

Comments 11

You must be signed in to comment.

  • Anas El Harda

    Anas El Harda

    Tried both method 1 & 2 with no sucess, the command i'm trying to run is

    "Add-DistributionGroupMember -Identity TestGroup -Member testuser1 -Confirm:$False"
    

    I see no errors thrown and when i check the TestGroup in O365 the user is not added.

    • Support

      Support

      Hello Anas,

      You can use the below script to add the target user to the group whose name is specified in the $groupName variable.

      Import-Module ExchangeOnlineManagement
      
      $groupName = "MyGroup" # TODO: modify me
      
      try
      {
          # Get the object ID in Office 365
          $objectId = [Guid]$Context.TargetObject.Get("adm-O365ObjectId")
      }
      catch
      {
          return # The user doesn't have an Office 365 account
      }
      
      Connect-ExchangeOnline -Credential $Context.GetOffice365Credential()
      
      # Add member to group
      try
      {
          Add-DistributionGroupMember $groupName -Member $objectId.ToString() -ErrorAction Stop
      }
      catch
      {
          $Context.LogMessage("An error occurred when adding the user to $groupName group. Error: " + $_.Exception.Message, "Warning")
      }
      

      If you need to automate membership in Office 365 groups, have a look at the following scripts from our repository: https://www.adaxes.com/script-repository/add-user-to-office-365-distribution-groups-based-on-business-unit-membership-s254.htm.

  • Nick Gatt

    Nick Gatt

    We just need to connect to 365 and run commands across all mailboxes, rather than the one in context. How is this achieved please? We need to connect to 365, and block IMAP/POP on all mailboxes. We then need to run the command weekly to remediate any mailboxes that might have been created insecurely. All ideas appreciated.

  • Stein Malmø

    Stein Malmø

    We've moved our cloud authentication to app registration, and recently updated to version 3.14.21404. After the update we received the error: "The cmdlet Connect-ExchangeOnline is not allowed. Use $Context.CloudServices.ConnectExchangeOnline() instead."

    So we rewrote some scripts to use $Context.CloudServices.ConnectExchangeOnline(), and it worked fine. But one script that runs as a scheduled task every 30 min fails after 2 runs, giving the error message ''Error while querying REST service. HttpStatusCode=401 ErrorMessage={"error":{"code":"TokenExpired","message":"The token has expired.","innerError":{"oAuthEventOperationId":"5856555c-e68c-49ab-9b2a-9c7543b4810b","oAuthEventcV":"uVu8+rB2YXgUWvv7zSNvCA.1.1","errorUrl":"https://aka.ms/autherrors#error-InvalidLifetime","requestId":"971a321c-726a-dd62-795f-53a40fd8c96b","date":"2023-06-29T01:28:03"}}} Stack trace: at , : line 6".

    I cannot find any way for us to manually refresh the exchange connection and its token. Is there such a possibility or are we doing something wrong?

    • Support

      Support

      Hello Malmo,

      Please, send us (support@adaxes.com) a screenshot of the scheduled task and the full script in TXT format. Any additional details will be much appreciated.

      • Stein Malmø

        Stein Malmø

        For others reading this post:
        The problem is in our use of the new EXO commandlets - in this instance Get-EXOMailbox. Adaxes support replied the following:

        We checked the behavior with Microsoft and it appears that there is a known issue with EXO cmdlets. They do not support multi-tenant usage. As such, they cannot be used in Adaxes at all. As of now, you need to replace all the EXO cmdlets in Adaxes scripts with the corresponding ones like in the example from our previous email. To find the scripts using the cmdlets, you can use the following approach: https://www.adaxes.com/script-repository/search-and-replace-text-in-adaxes-scripts-s224.htm.

  • Jo Schmitz

    Jo Schmitz

    Hello,
    is ther a way to use prefixes like in the exchange module?
    Example: Connect-ExchangeOnline -Credential XXXXX -Prefix O365
    Kind regards

    • Support

      Support

      Hello Jo,

      Unfortunately, there is no such possibility. However, it is not required. The $Context.CloudServices.ConnectExchangeOnline() method brings the permanent Exchange Online connection established by Adaxes into your script.

  • Jay Reyes

    Jay Reyes

    I'm running ADAXES 2023 and I get this error message when I try using the script above.

    Method invocation failed because [Softerra.Adaxes.Adsi.Scripting.ExecuteScriptActionConditionCloudServices] does not contain a method named 'ConnectExchangeOnline'.

    I'm just trying to convert a regular user mailbox to shared mailbox in O365. I've tried using the built in "Convert Mailbox" and that doesn't seem to work for me either.

    • Support

      Support

      Hello Jay,

      The error you are facing means that you are running an earlier Adaxes 2023 build where the ConnectExchangeOnline method does not exist yet. It was introduced in Adaxes 2023 Update 1. Moreover, the fact that you are facing errors converting a mailbox to a shared one using the built-in functionality means that Microsoft has followed through with its plan to deprecate remote PowerShell in Exchange Online, and it is not available in your tenant anymore. The Adaxes version you are using relies on PowerShell remoting to perform operations in Exchange Online, which means you need to update to a version that uses the Exchange Online Management V3 PowerShell module. You have a choice between upgrading to Adaxes 2023 Update 1 and upgrading to the latest version.

      Upgrade Instructions

      Adaxes 2023 Update 1
      Download
      What's New

      Adaxes 2023.2 Update 2
      Download
      What's New

Got questions?

Support Questions & Answers

We use cookies to improve your experience.
By your continued use of this site you accept such use.
For more details please see our privacy policy and cookies policy.