EWS Extension Online Powershell v3

Use the EWS Extension Online Powershell v3 integration to get information about mailboxes and users in your organization. This integration can also retrieve and modify Tenant Allow/Block Lists.

Email · Microsoft Exchange Online

Details

IDEWS Extension Online Powershell v3
ProviderMicrosoft
CategoryEmail
From Version5.5.0
Docker Imagedemisto/pwsh-exchangev3:1.0.0.11550820
Supported ModulesAgentix Cloud Runtime Security Cloud Posture Security XSIAM EDR Cortex Cloud

README

Use the EWS Extension Online Powershell v3 integration to get information about mailboxes and users in your organization.
This integration was integrated and tested with version v3 of EWS Extension Online Powershell v3

Note: This integration does not replace the O365 - EWS - Extension integration, but an additional EWS extension integration
which utilizes the EXO v3 module.

Configure EWS Extension Online Powershell v3 in Cortex

Parameter Description Required
Name The name of the integration True
Exchange Online URL https://outlook.office365.com True
Certificate A txt certificate encoded in Base64. True
The organization used in app-only authentication.   True
The application ID from the Azure portal   True

App authentication

To use this integration, you need to connect an application with a certificate.

  1. Create the application:
    1. Access Azure AD portal.
    2. Navigate to Home > App registrations.
    3. Click New Registration, give the application a name (for example: EWS) and click Register.
    4. In the left menu of the newly created application, click API permissions.
    5. Click Add a permission.
    6. In the Request API permissions page, click APIs my organization uses.
    7. Search for Office 365 Exchange Online.
    8. Click Application permissions.
    9. Under Exchange, click the ExchangeManageAsApp checkbox.
    10. Click Add permissions.
    11. Click Grant admin consent.
  2. Create the certificate in Cortex XSOAR/XSIAM.
    1. Run the CreateCertificate command in the Playground to acquire the certificate.

      !CreateCertificate days=<# of days> password=password

    Note: Remember your password since you will need it to create your integration instance.

    1. Download the certificateBase34.txt file.
    2. Open the downloaded txt file and copy the text.
    3. In the integration instance configuration, paste the text in the Certificate field.
  3. Attach the .cer file to your Azure app.
    1. In the Cortex XSOAR/XSIAM Playground, download the publickey.cer file
    2. In the Azure application, in the left menu, click Certificates & secrets.
    3. In the Certificates tab, upload the publickey.cer file.
  4. Assign Azure AD roles to the application.
    1. You have two options:
      • Assign Azure AD roles to the application.
      • Assign custom role groups to the application using service principals.
    2. In the Azure AD portal, search for Microsoft Entra roles and administrators in the Search box.
    3. On the Roles and administrators page that opens, find and select one of the supported roles by clicking on the
      name of the role (not the checkbox) in the results.
      • The role Security Administrator is eligible for this integration.
    4. On the Assignments page that opens, select Add assignments.
    5. In the Add assignments flyout that opens, find and select the app that you created in Step 1.

Note: The information in the Playground is sensitive information. You should delete the information by running the following command:

!DeleteContext all=yes

  1. In Cortex XSOAR/XSIAM, in the integration instance configuration, enter your saved password in the Password field.
  2. In Azure, go to Entra ID (Overview blade) and copy the Primary domain field.
  3. In Cortex XSOAR/XSIAM, in the integration instance configuration, paste the Domain name in The organization used in app-only authentication field.
  4. In the Azure app, navigate to Home > App registration > application name and copy the Application (client) ID.
  5. In Cortex XSOAR/XSIAM, in the integration instance configuration, paste the application ID in The application ID from the Azure portal field.

Verify that the admin account has sufficient Exchange Online permissions

For the integration to work, the Azure AD application’s service principal must have the correct permissions assigned in the Exchange Online role groups.

  1. Open the Microsoft Purview Portal: https://purview.microsoft.com/
  2. Log in using an admin account that can manage role assignments for the Azure AD application (for example, a Global Administrator or Privileged Role Administrator).
  3. In the top bar, select: Settings → Roles and scopes
  4. In the left sidebar, select: Role Groups
  5. Search for the following role groups:
    • Organization Management – the most privileged role and fully supported for this integration.
    • Security Administrator – a highly privileged security role that also provides full access.
  6. Open the role and verify that the service principal of the Azure AD application used by the integration is listed.
  7. If not listed, click Edit → Add Users and assign the required roles.

Troubleshooting and Testing

Common Issues and Solutions

The role assigned to application 'app-id' isn't supported in this scenario.

Scenario:
When running ‘Test’, you receive the error:
“The role assigned to application app-id isn’t supported in this scenario. Please check online documentation for assigning correct Directory Roles to Azure AD Application for EXO App-Only Authentication.”

Solution:
Verify that the application has the correct directory role assigned in the Entra ID portal.
See the “App authentication” section above for detailed guidance.


The term 'cmdlet' is not recognized as a name of a cmdlet…

Scenario:
When running a command, you receive an error similar to:
“The term cmdlet is not recognized as a name of a cmdlet, function, script file, or executable program…”

Solution:
Make sure the service principal of the Azure AD application used by the integration has sufficient Exchange Online permissions.
Refer to the “Exchange Online permissions” section above to confirm the correct roles are assigned and detailed guidance.

Commands

You can execute these commands from the CLI, as part of an automation, or in a playbook.
After you successfully execute a command, a DBot message appears in the War Room with the command details.

ews-mailbox-list


Displays mailbox objects and attributes, populate property pages, or supplies mailbox information to other tasks.

Base Command

ews-mailbox-list

Input

Argument Name Description Required
identity The identity of the mailbox you want to view. Optional
organizational_unit The object’s location in Active Directory by which to filter the results. Optional
primary_smtp_address The primary SMTP email address of the mailbox you want to view. Cannot be used with the user_principal_name argument. Can be retrieved using the ews-user-list command. Optional
user_principal_name The UPN of the mailbox you want to view. Cannot be used with the primary_smtp_address argument. Can be retrieved using the ews-user-list command. Optional
property_sets A comma-separated list of property sets to fetch. These property sets will supplement the outputs of this integration. Default is “Minimum”. Available properties are: “All”, “Minimum”, “AddressList”, “Archive”, “Audit”, “Delivery”, “Hold”, “Moderation”, “Move”, “Policy”, “PublicFolder”, “Quota”, “Resource”, “Retention”, “SCL”, “SoftDelete”, “StatisticsSeed”. Optional
limit The maximum number of results to retrieve. Default is 10. Default is 10. Optional

Context Output

Path Type Description
EWS.Mailbox.EmailAddresses String Email addresses of the mailbox.
EWS.Mailbox.AuditBypassEnabled Boolean Whether audit bypass is enabled.
EWS.Mailbox.DistinguishedName String Distinguished name of the mailbox.
EWS.Mailbox.ExchangeObjectId String Exchange object ID of the mailbox.
EWS.Mailbox.ExchangeVersion String Exchange version of the mailbox.
EWS.Mailbox.Guid String GUID of the mailbox.
EWS.Mailbox.Id String ID of the mailbox.
EWS.Mailbox.Identity String Identity of the mailbox.
EWS.Mailbox.IsValid Boolean Whether the mailbox is valid.
EWS.Mailbox.Name String Name of the mailbox.
EWS.Mailbox.ObjectCategory String Object category of the mailbox.
EWS.Mailbox.ObjectClass String Object class of the mailbox.
EWS.Mailbox.ObjectId String Object ID of the of the mailbox.
EWS.Mailbox.ObjectState String Object state of the mailbox.
EWS.Mailbox.OrganizationId String Organization ID of the mailbox.
EWS.Mailbox.OriginatingServer String Originating server of the mailbox.
EWS.Mailbox.PSComputerName String PowerShell computer name of the mailbox.
EWS.Mailbox.PSShowComputerName Boolean PowerShell show computer name of the mailbox.
EWS.Mailbox.RunspaceId String Run space ID of the mailbox.
EWS.Mailbox.WhenChanged Date Local time of when the mailbox was last changed.
EWS.Mailbox.WhenChangedUTC Date UTC time of when the mailbox was last changed.
EWS.Mailbox.WhenCreated Date Local time of when the mailbox was created.
EWS.Mailbox.WhenCreatedUTC Date UTC time of when the mailbox was created.

Command Example

!ews-mailbox-list limit=1

Context Example

{
    "EWS": {
        "Mailbox": {
            "Alias": "user",
            "DisplayName": "User User",
            "DistinguishedName": "CN=user,OU=example.com,OU=Microsoft Exchange Hosted Organizations,DC=EURPR07A005,DC=PROD,DC=OUTLOOK,DC=COM",
            "EmailAddresses": [
                "SPO:SPO_SPO0@SPO_SPO1",
                "SIP:user@example.com",
                "SMTP:user@example.com"
            ],
            "ExchangeVersion": "0.20 (15.0.0)",
            "ExternalDirectoryObjectId": "<ExternalDirectoryObjectId>",
            "Guid": "<Guid>",
            "Id": "user",
            "Identity": "user",
            "Name": "user",
            "OrganizationId": "EURPR07A005.PROD.OUTLOOK.COM/Microsoft Exchange Hosted Organizations/example.com - EURPR07A005.PROD.OUTLOOK.COM/ConfigurationUnits/example.com/Configuration",
            "PrimarySmtpAddress": "user@example.com",
            "RecipientType": "UserMailbox",
            "RecipientTypeDetails": "UserMailbox",
            "UserPrincipalName": "user@example.com"
        }
    }
}

Human Readable Output

Results of ews-mailbox-list

Alias DisplayName DistinguishedName EmailAddresses ExchangeVersion ExternalDirectoryObjectId Guid Id Identity Name OrganizationId PrimarySmtpAddress RecipientType RecipientTypeDetails UserPrincipalName
“user” “User User” “CN=user,OU=example.com,OU=Microsoft Exchange Hosted Organizations,DC=EURPR07A005,DC=PROD,DC=OUTLOOK,DC=COM” [“SPO:SPO_cac4b654-5fcf-44f0-818e-479cf8ae42ac@SPO_SP01”,”SIP:user@example.com”,”SMTP:user@example.com”] “0.20 (15.0.0)” “3fa9f28b-eb0e-463a-ba7b-8089fe9991e2” {“value”:”042e60ea-0683-41a2-a149-ca4b682dcdda”,”Guid”:”042e60ea-0683-41a2-a149-ca4b682dcdda”} “user” “user” “user” “EURPR07A005.PROD.OUTLOOK.COM/Microsoft Exchange Hosted Organizations/example.com - EURPR07A005.PROD.OUTLOOK.COM/ConfigurationUnits/example.com/Configuration” “user@example.com” “UserMailbox” “UserMailbox” “user@example.com”

ews-cas-mailbox-list


Displays Client Access settings that are configured on mailboxes.

Base Command

ews-cas-mailbox-list

Input

Argument Name Description Required
identity The identity of the mailbox you want to view. Optional
organizational_unit The object’s location in Active Directory by which to filter the results. Optional
primary_smtp_address The primary SMTP email address of the mailbox you want to view. Cannot be used with the user_principal_name argument. Can be retrieved using the ews-user-list command. Optional
user_principal_name The UPN of the mailbox you want to view. Cannot be used with the primary_smtp_address argument. Can be retrieved using the ews-user-list command. Optional
limit The maximum number of results to retrieve. Default is 10. Default is 10. Optional

Context Output

Path Type Description
EWS.CASMailbox.ActiveSyncEnabled Boolean Whether active sync is enabled.
EWS.CASMailbox.DisplayName String The display name of the mailbox.
EWS.CASMailbox.ECPEnabled Boolean Whether the Exchange Control Panel (ECP) is enabled.
EWS.CASMailbox.EmailAddresses String The email addresses retrieved.
EWS.CASMailbox.EwsEnabled Boolean Whether the Exchange Web Services (EWS) is enabled.
EWS.CASMailbox.ExchangeVersion String Exchange version of the client access server mailbox.
EWS.CASMailbox.ExternalDirectoryObjectId String External directory object ID of the client access server mailbox.
EWS.CASMailbox.Guid String The GUID of the client access server mailbox.
EWS.CASMailbox.Identity String Identity of the client access server mailbox.
EWS.CASMailbox.ImapEnabled Boolean Whether the Internet Message Access Protocol (IMAP) is enabled.
EWS.CASMailbox.MAPIEnabled Boolean Whether the Messaging Application Programming Interface is enabled.
EWS.CASMailbox.Name String Name of the client access server mailbox.
EWS.CASMailbox.OWAEnabled Boolean Whether Outlook on the web (OWA) is enabled.
EWS.CASMailbox.OrganizationId String Organization ID
EWS.CASMailbox.PopEnabled Boolean Whether Post Office Protocol (POP) is enabled.
EWS.CASMailbox.PrimarySmtpAddress String Primary SMTP address.
EWS.CASMailbox.ServerLegacyDN String Server legacy distinguished name (DN).

Command Example

!ews-cas-mailbox-list limit=1

Context Example

{
    "EWS": {
        "CASMailbox": {
            "ActiveSyncEnabled": true,
            "DisplayName": "User User",
            "ECPEnabled": true,
            "EmailAddresses": [
                "SPO:SPO_SPO0@SPO_SPO1",
                "SIP:user@example.com",
                "SMTP:user@example.com"
            ],
            "EwsEnabled": true,
            "ExchangeVersion": "0.20 (15.0.0)",
            "ExternalDirectoryObjectId": "<ExternalDirectoryObjectId>",
            "Guid": "<Guid>",
            "Identity": "user",
            "ImapEnabled": true,
            "MAPIEnabled": true,
            "Name": "user",
            "OWAEnabled": true,
            "OrganizationId": "EURPR07A005.PROD.OUTLOOK.COM/Microsoft Exchange Hosted Organizations/example.com - EURPR07A005.PROD.OUTLOOK.COM/ConfigurationUnits/example.com/Configuration",
            "PopEnabled": true,
            "PrimarySmtpAddress": "user@example.com",
            "ServerLegacyDN": "/o=ExchangeLabs/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Configuration/cn=Servers/cn=DBXPR07MB383"
        }
    }
}

Human Readable Output

Results of ews-cas-mailbox-list

ActiveSyncEnabled DisplayName ECPEnabled EmailAddresses EwsEnabled ExchangeVersion ExternalDirectoryObjectId Guid Identity ImapEnabled MAPIEnabled Name OrganizationId OWAEnabled PopEnabled PrimarySmtpAddress ServerLegacyDN
true “User User” true [“SPO:SPO_cac4b654-5fcf-44f0-818e-479cf8ae42ac@SPO_SP01”,”SIP:user@example.com”,”SMTP:user@example.com”] true “0.20 (15.0.0)” “3fa9f28b-eb0e-463a-ba7b-8089fe9991e2” {“value”:”042e60ea-0683-41a2-a149-ca4b682dcdda”,”Guid”:”042e60ea-0683-41a2-a149-ca4b682dcdda”} “user” true true “user” “EURPR07A005.PROD.OUTLOOK.COM/Microsoft Exchange Hosted Organizations/example.com - EURPR07A005.PROD.OUTLOOK.COM/ConfigurationUnits/example.com/Configuration” true true “user@example.com” “/o=ExchangeLabs/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Configuration/cn=Servers/cn=DBXPR07MB383

ews-mailbox-permission-list


Retrieves permissions on a mailbox.

Base Command

ews-mailbox-permission-list

Input

Argument Name Description Required
identity The identity of the mailbox you want to view. Required

Context Output

Path Type Description
EWS.MailboxPermission.Identity String The specified identity of the mailbox.
EWS.MailboxPermission.Permission.AccessRights String Access rights of the mailbox.
EWS.MailboxPermission.Permission.Deny.IsPresent Boolean Whether permission is denied.
EWS.MailboxPermission.Permission.Identity String The permission identity.
EWS.MailboxPermission.Permission.InheritanceType String Permission inheritance type.
EWS.MailboxPermission.Permission.IsInherited Boolean Whether permission is inherited.
EWS.MailboxPermission.Permission.User String The permission of the user.

Command Example

!ews-mailbox-permission-list identity=user

Context Example

{
    "EWS": {
        "MailboxPermission": {
            "Identity": "user",
            "Permission": {
                "AccessRights": [
                    "FullAccess",
                    "ReadPermission"
                ],
                "Deny": {
                    "IsPresent": false
                },
                "Identity": "user",
                "InheritanceType": "All",
                "IsInherited": false,
                "User": "NT AUTHORITY\\SELF"
            }
        }
    }
}

Human Readable Output

Results of ews-mailbox-permission-list

AccessRights Deny Identity InheritanceType IsInherited User
[“FullAccess”,”ReadPermission”] {“IsPresent”:false} “user” “All” false “NT AUTHORITY\SELF”

ews-recipient-permission-list


Displays information about SendAs permissions that are configured for users.

Base Command

ews-recipient-permission-list

Input

Argument Name Description Required
identity The identity of the mailbox you want to view. Optional
limit The maximum number of results to retrieve. Default is 10. Default is 10. Optional

Context Output

Path Type Description
EWS.RecipientPermission.AccessControlType String Access control type of the recipient permission.
EWS.RecipientPermission.AccessRights Number Access rights of the recipient permission.
EWS.RecipientPermission.Identity String Identity of the recipient permission.
EWS.RecipientPermission.InheritanceType String Inheritance type of the recipient permission.
EWS.RecipientPermission.IsInherited Boolean Whether the recipient permission is inherited.
EWS.RecipientPermission.Trustee String Trustee of the recipient permission.

Command Example

!ews-recipient-permission-list identity=<Guid>

Context Example

{
    "EWS": {
        "RecipientPermission": {
            "AccessControlType": "Allow",
            "AccessRights": [
                1
            ],
            "Identity": "user",
            "InheritanceType": "None",
            "IsInherited": false,
            "Trustee": "NT AUTHORITY\\SELF"
        }
    }
}

Human Readable Output

Results of ews-mailbox-permission-list

AccessRights Deny Identity InheritanceType IsInherited User
[“FullAccess”,”ReadPermission”] {“IsPresent”:false} “user” “All” false “NT AUTHORITY\SELF”

ews-recipient-list


Displays existing recipient objects in your organization. This command returns all mail-enabled objects (for example, mailboxes, mail users, mail contacts, and distribution groups).

Base Command

ews-recipient-list

Input

Argument Name Description Required
identity The identity of the mailbox you want to view. Optional
limit The maximum number of results to retrieve. Default is 10. Default is 10. Optional

Context Output

Path Type Description
EWS.Recipient.Alias String Recipient alias.
EWS.Recipient.DisplayName String Recipient display name.
EWS.Recipient.DistinguishedName String Recipient distinguished name.
EWS.Recipient.EmailAddresses String Recipient email addresses.
EWS.Recipient.ExchangeVersion String Recipient exchange version.
EWS.Recipient.ExternalDirectoryObjectId String Recipient external directory object ID.
EWS.Recipient.Identity String Recipient identity.
EWS.Recipient.Name String Recipient name.
EWS.Recipient.OrganizationId String Recipient organization ID.
EWS.Recipient.PrimarySmtpAddress String Recipient primary SMTP address.
EWS.Recipient.RecipientType String Recipient type.
EWS.Recipient.RecipientTypeDetails String Recipient type details.

Command Example

!ews-recipient-list identity=<ExternalDirectoryObjectId>

Context Example

{
    "EWS": {
        "Recipient": {
            "Alias": "user",
            "DisplayName": "User User",
            "DistinguishedName": "CN=user,OU=example.com,OU=Microsoft Exchange Hosted Organizations,DC=EURPR07A005,DC=PROD,DC=OUTLOOK,DC=COM",
            "EmailAddresses": [
                "SPO:SPO_SPO0@SPO_SPO1",
                "SIP:user@example.com",
                "SMTP:user@example.com"
            ],
            "ExchangeVersion": "0.20 (15.0.0)",
            "ExternalDirectoryObjectId": "<ExternalDirectoryObjectId>",
            "Identity": "user",
            "Name": "user",
            "OrganizationId": "EURPR07A005.PROD.OUTLOOK.COM/Microsoft Exchange Hosted Organizations/example.com - EURPR07A005.PROD.OUTLOOK.COM/ConfigurationUnits/example.com/Configuration",
            "PrimarySmtpAddress": "user@example.com",
            "RecipientType": "UserMailbox",
            "RecipientTypeDetails": "UserMailbox"
        }
    }
}

Human Readable Output

Results of ews-recipient-list

Alias DisplayName DistinguishedName EmailAddresses ExchangeVersion ExternalDirectoryObjectId Identity Name OrganizationId PrimarySmtpAddress RecipientType RecipientTypeDetails
“user” “user” “CN=user_Identity,OU=example.com,OU=Microsoft Exchange Hosted Organizations,DC=EURPR07A005,DC=PROD,DC=OUTLOOK,DC=COM” [“SPO:SPO_SP00@SPO_SP01”,”SMTP:user@example.com”] “0.10 (14.0.100)” “Identity” “user_Identity” “user_Identity” “EURPR07A005.PROD.OUTLOOK.COM/Microsoft Exchange Hosted Organizations/example.com - EURPR07A005.PROD.OUTLOOK.COM/ConfigurationUnits/example.com/Configuration” “user@example.com” “MailUniversalDistributionGroup” “GroupMailbox”

ews-new-tenant-allow-block-list-items


Add new items to the Tenant Allow/Block Lists. Uses PowerShell New-TenantAllowBlockListItems cmdlet.

Official PowerShell cmdlet documentation here

Base Command

ews-new-tenant-allow-block-list-items

Input

Argument Name Description Required
entries Entries to add to the list. Separate multiple entries with a comma (e.g. “Item1,Item2”). Required
list_type List type to add items to. Required
list_subtype List subtype to add items to. Optional
action Action to set for new entries Required
notes Notes to include on new list entries Optional
expiration_date Enter a specific date and time for the new entries to expire using format “YYYY-MM-DD HH:MM:SSz” for UTC time. Alternately, a PowerShell GetDate statement can be used. Optional
no_expiration Specify whether to create list entries with no expiration date. Cannot be used with “expiration_date”. If left false and no expiration date is set, default of 30 days will be used. Optional

Context Output

Path Type Description
EWS.NewTenantBlocks.Action String List type (‘Block’ or ‘Allow’)
EWS.NewTenantBlocks.EntryValueHash String Entry Value Hash
EWS.NewTenantBlocks.Error String Error (if any) returned by remote command
EWS.NewTenantBlocks.ExpirationDate String DateTime the entry will expire and be removed
EWS.NewTenantBlocks.Identity String Unique identifier for the entry
EWS.NewTenantBlocks.LastModifiedDateTime String DateTime of last modification
EWS.NewTenantBlocks.ListSubType String List sub type (Tenant or AdvancedDelivery)
EWS.NewTenantBlocks.ModifiedBy String User / App Registration which last modified this entry
EWS.NewTenantBlocks.Notes String Custom notes added to the entry.
EWS.NewTenantBlocks.ObjectState String State of the object (e.g. New/Modified/Deleted)
EWS.NewTenantBlocks.PSComputerName String Name of Remote Powershell endpoint
EWS.NewTenantBlocks.PSShowComputerName Bool Flag whether or not remote computer name is shown in PS prompt
EWS.NewTenantBlocks.RunspaceId String RunspaceID of the entry
EWS.NewTenantBlocks.SubmissionID String SubmissionID of the entry
EWS.NewTenantBlocks.SysManaged Bool SysManaged property of the entry
EWS.NewTenantBlocks.Value String The value of the new entry created

Command Example

!ews-new-tenant-allow-block-list-items action=Block list_type=sender entries="attacker@phishingsite.com" notes="Email observed in a phishing campaign."

Context Example

{
    "Action": "Block",
    "EntryValueHash": "d568L6iokOxrYqB2L1CxcKy6S6A/tCDoQQJal33AFWo=",
    "Error": null,
    "ExpirationDate": "2022-06-15T19:30:52.6071551Z",
    "Identity": "RgAAAAAuoyIuRcZsTKgZbIQyJWZUBwA02rlnO0nOR5RO-QI-xRP9AAAAAAEVAAA02rlnO0nOR5RO-QI-xRP9AAADfzPhAAAA0",
    "LastModifiedDateTime": "2022-05-16T19:30:52.7320883Z",
    "ListSubType": "Tenant",
    "ModifiedBy": "",
    "Notes": "Email observed in a phishing campaign.",
    "ObjectState": "New",
    "PSComputerName": "outlook.office365.com",
    "PSShowComputerName": false,
    "RunspaceId": "fe0186a8-6ce6-487d-bd65-a9869f60ffcd",
    "SubmissionID": "",
    "SysManaged": false,
    "Value": "attacker@phishingsite.com"
}

Human Readable Output

Results of ews-new-tenant-allow-block-list-items

Action EntryValueHash Error ExpirationDate Identity LastModifiedDateTime ListSubType ModifiedBy Notes ObjectState PSComputerName PSShowComputerName RunspaceId SubmissionID SysManaged Value
Block d568L6iokOxrYqB2L1CxcKy6S6A/tCDoQQJal33AFWo=   {“value”:”2022-06-15T19:34:01.2028448Z”,”DateTime”:”Wednesday, June 15, 2022 7:34:01 PM”} RgAAAAAuoyIuRcZsTKgZbIQyJWZUBwA02rlnO0nOR5RO-QI-xRP9AAAAAAEVAAA02rlnO0nOR5RO-QI-xRP9AAADfzPiAAAA0 {“value”:”2022-05-16T19:34:01.2652934Z”,”DateTime”:”Monday, May 16, 2022 7:34:01 PM”} Tenant   Email observed in a phishing campaign. New outlook.office365.com false {“value”:”8f736b87-f951-4b6b-aa21-e358720c44e3”,”Guid”:”8f736b87-f951-4b6b-aa21-e358720c44e3”}   false attacker@phishingsite.com

ews-get-tenant-allow-block-list-items


Retrieve current Tenant Allow/Block List items. Uses Get-TenantAllowBlockListItems cmdlet.

Official PowerShell cmdlet documentation here

Base Command

ews-get-tenant-allow-block-list-items

Input

Argument Name Description Required
list_type List type to retrieve items from. Required
list_subtype List subtype to retrieve items from. Optional
action Action to filter entries by. Required
expiration_date Enter a specific date and time to filter entries by using format “YYYY-MM-DD HH:MM:SSz” for UTC time. Alternately, a PowerShell GetDate statement can be used. Optional
no_expiration Filter list items that are set to never expire. Optional
entry Specific entry value to retrieve. Optional

Context Output

Path Type Description
EWS.CurrentTenantBlocks.Action String List type (‘Block’ or ‘Allow’)
EWS.CurrentTenantBlocks.EntryValueHash String Entry Value Hash
EWS.CurrentTenantBlocks.Error Bool Error (if any) returned by remote command
EWS.CurrentTenantBlocks.ExpirationDate String DateTime the entry will expire and be removed
EWS.CurrentTenantBlocks.Identity String Unique identifier for the entry
EWS.CurrentTenantBlocks.LastModifiedDateTime String DateTime of last modification
EWS.CurrentTenantBlocks.ListSubType String List sub type (Tenant or AdvancedDelivery)
EWS.CurrentTenantBlocks.ModifiedBy String User / App Registration which last modified this entry
EWS.CurrentTenantBlocks.Notes String Custom notes added to the entry.
EWS.CurrentTenantBlocks.ObjectState String State of the object (e.g. New/Modified/Deleted)
EWS.CurrentTenantBlocks.PSComputerName String Name of Remote Powershell endpoint
EWS.CurrentTenantBlocks.PSShowComputerName Bool Flag whether or not remote computer name is shown in PS prompt
EWS.CurrentTenantBlocks.RunspaceId String RunspaceID of the entry
EWS.CurrentTenantBlocks.SubmissionID String SubmissionID of the entry
EWS.CurrentTenantBlocks.SysManaged Bool SysManaged property of the entry
EWS.CurrentTenantBlocks.Value String The value of the new entry created

Command Example

!ews-get-tenant-allow-block-list-items action=Block list_type=sender

Context Example

[
    {
        "Action": "Block",
        "EntryValueHash": "d568L6iokOxrYqB2L1CxcKy6S6A/tCDoQQJal33AFWo=",
        "Error": null,
        "ExpirationDate": "2022-06-15T19:34:01.2028448Z",
        "Identity": "RgAAAAAuoyIuRcZsTKgZbIQyJWZUBwA02rlnO0nOR5RO-QI-xRP9AAAAAAEVAAA02rlnO0nOR5RO-QI-xRP9AAADfzPiAAAA0",
        "LastModifiedDateTime": "2022-05-16T19:34:01.2652934Z",
        "ListSubType": "Tenant",
        "ModifiedBy": "",
        "Notes": "Email observed in a phishing campaign.",
        "ObjectState": "Unchanged",
        "PSComputerName": "outlook.office365.com",
        "PSShowComputerName": false,
        "RunspaceId": "010da4cf-2d47-4b8a-a882-4bd6885faff1",
        "SubmissionID": "",
        "SysManaged": false,
        "Value": "attacker@phishingsite.com"
    }
]

Human Readable Output

Results of ews-get-tenant-allow-block-list-items

Action EntryValueHash Error ExpirationDate Identity LastModifiedDateTime ListSubType ModifiedBy Notes ObjectState PSComputerName PSShowComputerName RunspaceId SubmissionID SysManaged Value
Block d568L6iokOxrYqB2L1CxcKy6S6A/tCDoQQJal33AFWo=   {“value”:”2022-06-15T19:34:01.2028448Z”,”DateTime”:”Wednesday, June 15, 2022 7:34:01 PM”} RgAAAAAuoyIuRcZsTKgZbIQyJWZUBwA02rlnO0nOR5RO-QI-xRP9AAAAAAEVAAA02rlnO0nOR5RO-QI-xRP9AAADfzPiAAAA0 {“value”:”2022-05-16T19:34:01.2652934Z”,”DateTime”:”Monday, May 16, 2022 7:34:01 PM”} Tenant   Email observed in a phishing campaign. Unchanged outlook.office365.com false {“value”:”feada07c-99b7-48e9-a562-a755073522ff”,”Guid”:”feada07c-99b7-48e9-a562-a755073522ff”}   false attacker@phishingsite.com

ews-get-tenant-allow-block-list-count


Retrieve current count of defined Tenant Allow/Block List items. Uses Get-TenantAllowBlockListItems cmdlet.

Official PowerShell cmdlet documentation here

Base Command

ews-get-tenant-allow-block-list-count

Input

Argument Name Description Required
list_type List type to retrieve items from. Optional
list_subtype List subtype to retrieve items from. Optional

Context Output

Path Type Description
EWS.CurrentListCount.Count Number Number of entries presently in the specified list
EWS.CurrentListCount.ListSubType String List sub type (Tenant or AdvancedDelivery)
EWS.CurrentListCount.ListType String List type

Command Example

!ews-get-tenant-allow-block-list-count list_type=sender

Context Example

{
    "Count": 2,
    "ListSubType": "Tenant",
    "ListType": "sender"
}

Human Readable Output

Results of ews-get-tenant-allow-block-list-count

Count ListSubType ListType
2 Tenant sender

ews-remove-tenant-allow-block-list-items


Remove items from the Tenant Allow/Block Lists. You can delete items by their value or by unique ID. Uses PowerShell cmdlet Remove-TenantAllowBlockListItems cmdlet.

Official PowerShell cmdlet documentation here

Base Command

ews-remove-tenant-allow-block-list-items

Input

Argument Name Description Required
entries Entries to remove from the list. Either use this OR ‘ids’ to specify items to remove. Separate multiple entries with a comma (e.g. “Item1,Item2”). Optional
ids Entry IDs to remove from the list. Either use this OR ‘entries’ to specify items to remove. Separate multiple entries with a comma (e.g. “Item1,Item2”). Optional
list_type List type to remove items from. Required
list_subtype List subtype to remove items from. Optional

Context Output

Path Type Description
EWS.RemovedTenantBlocks.Action String Action
EWS.RemovedTenantBlocks.EntryValueHash String Null for deleted items.
EWS.RemovedTenantBlocks.Error String Null for deleted items.
EWS.RemovedTenantBlocks.ExpirationDate String Null for deleted items.
EWS.RemovedTenantBlocks.Identity String Blank for deleted items.
EWS.RemovedTenantBlocks.LastModifiedDateTime String Null for deleted items.
EWS.RemovedTenantBlocks.ListSubType String Null for deleted items.
EWS.RemovedTenantBlocks.ModifiedBy String Null for deleted items.
EWS.RemovedTenantBlocks.Notes String Null for deleted items.
EWS.RemovedTenantBlocks.ObjectState String State of the object (Deleted)
EWS.RemovedTenantBlocks.PSComputerName String Name of Remote Powershell endpoint
EWS.RemovedTenantBlocks.PSShowComputerName Bool Flag whether or not remote computer name is shown in PS prompt
EWS.RemovedTenantBlocks.RunspaceId String RunspaceID of the entry
EWS.RemovedTenantBlocks.SubmissionID String SubmissionID of the entry
EWS.RemovedTenantBlocks.SysManaged Bool SysManaged property of the entry
EWS.RemovedTenantBlocks.Value String The value of the entry that was removed

Command Example

!ews-remove-tenant-allow-block-list-items list_type=sender entries="attacker2@phishingsite.com"

Context Example

{
    "Action": "0",
    "EntryValueHash": null,
    "Error": null,
    "ExpirationDate": null,
    "Identity": "",
    "LastModifiedDateTime": null,
    "ListSubType": null,
    "ModifiedBy": null,
    "Notes": null,
    "ObjectState": "Deleted",
    "PSComputerName": "outlook.office365.com",
    "PSShowComputerName": false,
    "RunspaceId": "efa88be5-7342-4b77-af2f-99dd2d914300",
    "SubmissionID": null,
    "SysManaged": null,
    "Value": "attacker2@phishingsite.com"
}

Human Readable Output

Results of ews-remove-tenant-allow-block-list-items

Action EntryValueHash Error ExpirationDate Identity LastModifiedDateTime ListSubType ModifiedBy Notes ObjectState PSComputerName PSShowComputerName RunspaceId SubmissionID SysManaged Value
0                 Deleted outlook.office365.com false {“value”:”cd58060e-d033-4cdb-814e-9f9748fdf78c”,”Guid”:”cd58060e-d033-4cdb-814e-9f9748fdf78c”}     attacker@phishingsite.com

ews-export-quarantinemessage


Export quarantine messages.

Base Command

ews-export-quarantinemessage

Input

Argument Name Description Required
identities A comma-separated list of identities of the messages to export. Optional
identity The identity of a single message to export. Optional
compress_output Specify whether the output should be compressed. Optional
entity_type The type of entity being exported. Optional
force_conversion_to_mime Specify whether to force conversion to MIME format. Optional
password Password to encrypt the exported file. Using this argument requires ‘compress_output’ argument to be set to true. Optional
reason_for_export Reason for exporting the message. Using this argument requires ‘compress_output’ argument to be set to true. Optional
recipient_address Filters the results by the recipient’s email address. Optional

Context Output

Path Type Description
EWS.ExportQuarantineMessage.BodyEncoding String Encoding used for the body of the message.
EWS.ExportQuarantineMessage.Eml String The email message in Base64 encoding.
EWS.ExportQuarantineMessage.Identity String Unique identifier for the retrieved message.
EWS.ExportQuarantineMessage.Organization Boolean Identifier for the organization associated with the message.

Command Example

!ews-export-quarantinemessage identity="12345678-beef-dead-beef-0123456789ab\\c0ffee13-beef-dead-beef-0123456789ab"

Context Example

{
    "BodyEncoding": "Base64",
    "Eml": "TmV2ZXIgZ29ubmEgZ2l2ZSB5b3UgdXAsIG5ldmVyIGdvbm5hIGxldCB5b3UgZG93biwgbmV2ZXIgZ29ubmEgcnVuIGFyb3VuZCBhbmQgZGVzZXJ0IHlvdQo=",
    "Identity": "12345678-beef-dead-beef-0123456789ab\\c0ffee13-beef-dead-beef-0123456789ab",
    "Organization": "c0ffee13-beef-dead-beef-0123456789ab"
}

Human Readable Output

Results of ews-export-quarantinemessage

BodyEncoding Eml Identity Organization
Base64 TmV2ZXIgZ29ubmEgZ2l2ZSB5b3UgdXAsIG5ldmVyIGdvbm5hIGxldCB5b3UgZG93biwgbmV2ZXIgZ29ubmEgcnVuIGFyb3VuZCBhbmQgZGVzZXJ0IHlvdQo= 12345678-beef-dead-beef-0123456789ab\c0ffee13-beef-dead-beef-0123456789ab c0ffee13-beef-dead-beef-0123456789ab

ews-get-quarantinemessage


Retrieve quarantine messages.

Base Command

ews-get-quarantinemessage

Input

Argument Name Description Required
identity The identity of a single message to retrieve. Optional
entity_type Filters by entity workload type. Optional
recipient_address Filters by the recipient email address. Optional
sender_address Filters by the sender email address. Optional
teams_conversation_types Filters by one or more Teams conversation types. Deprecated, as this parameter is not available in the PowerShell type used in this integration. Optional
direction The message direction (inbound or outbound). Optional
domain Domain associated with the message. Optional
end_expires_date End date for the message expiration. Optional
end_received_date The end of the received message date range. Supports the format ‘MM/dd/yyyy HH:mm:ss’. Optional
include_messages_from_blocked_sender_address Whether to include messages from blocked sender addresses. Optional
message_id The internet message ID (client ID) found in the email headers. Optional
my_items Include only items belonging to the user. Optional
page Page number for pagination. Optional
page_size The number of items per page. Maximum is 1000. Default is 50. Optional
policy_name Name of the policy associated with the message. Optional
policy_types Filter by types of policies. Optional
quarantine_types Filters by one or more quarantine types. Optional
recipient_tag Filters by the priority tag associated with the recipient. Optional
release_status Filters by the message release status. Optional
reported Whether to include only reported messages. Optional
start_expires_date Start date for the message expiration. Optional
start_received_date The start of the received message date range. Supported format ‘MM/dd/yyyy HH:mm:ss’. Optional
subject Subject of the message. Optional
type Type of the message. Optional

Context Output

Path Type Description
EWS.GetQuarantineMessage.ApprovalId string Approval ID of the message.
EWS.GetQuarantineMessage.ApprovalUPN string User Principal Name (UPN) of the approver.
EWS.GetQuarantineMessage.CustomData unknown Custom data associated with the message.
EWS.GetQuarantineMessage.DeletedForRecipients string List of recipients for whom the message was deleted.
EWS.GetQuarantineMessage.Direction string Direction of the message (Inbound/Outbound).
EWS.GetQuarantineMessage.EntityType string Entity type of the message.
EWS.GetQuarantineMessage.Expires date Expiry date of the message.
EWS.GetQuarantineMessage.Identity string Unique identifier for the message.
EWS.GetQuarantineMessage.MessageId string Message ID of the email.
EWS.GetQuarantineMessage.MoveToQuarantineAdminActionTakenBy string Admin action taken by.
EWS.GetQuarantineMessage.MoveToQuarantineApprovalId string Approval ID for moving to quarantine.
EWS.GetQuarantineMessage.Organization string Identifier for the organization associated with the message.
EWS.GetQuarantineMessage.OverrideReason string Reason for overriding the message.
EWS.GetQuarantineMessage.OverrideReasonIntValue number Integer value of the override reason.
EWS.GetQuarantineMessage.PermissionToAllowSender boolean Permission to allow the sender.
EWS.GetQuarantineMessage.PermissionToBlockSender boolean Permission to block the sender.
EWS.GetQuarantineMessage.PermissionToDelete boolean Permission to delete the message.
EWS.GetQuarantineMessage.PermissionToDownload boolean Permission to download the message.
EWS.GetQuarantineMessage.PermissionToPreview boolean Permission to preview the message.
EWS.GetQuarantineMessage.PermissionToRelease boolean Permission to release the message.
EWS.GetQuarantineMessage.PermissionToRequestRelease boolean Permission to request release of the message.
EWS.GetQuarantineMessage.PermissionToViewHeader boolean Permission to view the header of the message.
EWS.GetQuarantineMessage.PolicyName string Name of the policy applied to the message.
EWS.GetQuarantineMessage.PolicyType string Type of the policy applied to the message.
EWS.GetQuarantineMessage.QuarantineTypes string Types of quarantine applied to the message.
EWS.GetQuarantineMessage.QuarantinedUser string List of users quarantined.
EWS.GetQuarantineMessage.ReceivedTime date Time the message was received.
EWS.GetQuarantineMessage.RecipientAddress string List of recipient email addresses.
EWS.GetQuarantineMessage.RecipientCount number Number of recipients.
EWS.GetQuarantineMessage.RecipientTag string Tags associated with the recipient.
EWS.GetQuarantineMessage.ReleaseStatus string Release status of the message.
EWS.GetQuarantineMessage.Released boolean Whether the message was released.
EWS.GetQuarantineMessage.ReleasedBy string List of users who released the message.
EWS.GetQuarantineMessage.ReleasedCount number Number of times the message was released.
EWS.GetQuarantineMessage.ReleasedUser string List of users who released the message.
EWS.GetQuarantineMessage.Reported boolean Whether the message was reported.
EWS.GetQuarantineMessage.SenderAddress string Email address of the sender.
EWS.GetQuarantineMessage.Size number Size of the message in bytes.
EWS.GetQuarantineMessage.SourceId string Source ID of the message.
EWS.GetQuarantineMessage.Subject string Subject of the message.
EWS.GetQuarantineMessage.SystemReleased boolean Whether the system released the message.
EWS.GetQuarantineMessage.TagName string Tag name associated with the message.
EWS.GetQuarantineMessage.TeamsConversationType string Teams conversation type associated with the message.
EWS.GetQuarantineMessage.Type string Type of the message.

Command Example


#### Context Example

```json
{
[
    {
        "ApprovalId": "",
        "ApprovalUPN": "",
        "CustomData": null,
        "DeletedForRecipients": [],
        "Direction": "Outbound",
        "EntityType": "Email",
        "Expires": "2024-07-18T13:20:02.7166413+00:00",
        "Identity": "12345678-beef-dead-beef-0123456789ab\\c0ffee13-beef-dead-beef-0123456789ab",
        "MessageId": "\u003c12345678-beef-dead-beef-0123456789ab@123456.789a.bcde.example.com\u003e",
        "MoveToQuarantineAdminActionTakenBy": "",
        "MoveToQuarantineApprovalId": "",
        "Organization": "c0ffee13-beef-dead-beef-0123456789ab",
        "OverrideReason": "None",
        "OverrideReasonIntValue": 0,
        "PermissionToAllowSender": true,
        "PermissionToBlockSender": false,
        "PermissionToDelete": true,
        "PermissionToDownload": true,
        "PermissionToPreview": true,
        "PermissionToRelease": true,
        "PermissionToRequestRelease": false,
        "PermissionToViewHeader": false,
        "PolicyName": "Default",
        "PolicyType": "HostedContentFilterPolicy",
        "QuarantineTypes": "HighConfPhish",
        "QuarantinedUser": [],
        "ReceivedTime": "2024-07-02T13:20:02.7166413+00:00",
        "RecipientAddress": [
            "admin@example.com"
        ],
        "RecipientCount": 1,
        "RecipientTag": [
            ""
        ],
        "ReleaseStatus": "NOTRELEASED",
        "Released": false,
        "ReleasedBy": [],
        "ReleasedCount": 0,
        "ReleasedUser": [],
        "Reported": false,
        "SenderAddress": "alerts@example.com",
        "Size": 31218,
        "SourceId": "",
        "Subject": "Informational-severity alert: Tenant Allow/Block List entry is about to expire",
        "SystemReleased": false,
        "TagName": "AdminOnlyAccessPolicy",
        "TeamsConversationType": "",
        "Type": "High Confidence Phish"
    },
    {
        "ApprovalId": "",
        "ApprovalUPN": "",
        "CustomData": null,
        "DeletedForRecipients": [],
        "Direction": "Inbound",
        "EntityType": "Email",
        "Expires": "2024-07-13T10:59:12.7581841+00:00",
        "Identity": "12345678-beef-dead-beef-0123456789ac\\c0ffee13-beef-dead-beef-0123456789ac",
        "MessageId": "\u003c12345678-beef-dead-beef-0123456789ac@123456.789a.bcde.example.com\u003e",
        "MoveToQuarantineAdminActionTakenBy": "",
        "MoveToQuarantineApprovalId": "",
        "Organization": "c0ffee13-beef-dead-beef-0123456789ac",
        "OverrideReason": "None",
        "OverrideReasonIntValue": 0,
        "PermissionToAllowSender": true,
        "PermissionToBlockSender": false,
        "PermissionToDelete": true,
        "PermissionToDownload": true,
        "PermissionToPreview": true,
        "PermissionToRelease": true,
        "PermissionToRequestRelease": false,
        "PermissionToViewHeader": false,
        "PolicyName": "testing_quarantine_release",
        "PolicyType": "HostedContentFilterPolicy",
        "QuarantineTypes": "HighConfPhish",
        "QuarantinedUser": [],
        "ReceivedTime": "2024-06-28T10:59:12.7581841+00:00",
        "RecipientAddress": [
            "user@example.com"
        ],
        "RecipientCount": 1,
        "RecipientTag": [
            ""
        ],
        "ReleaseStatus": "RELEASED",
        "Released": true,
        "ReleasedBy": [
            "SystemMailbox{deadbeef-dead-beef-dead-beefdeadbeef}@example.com"
        ],
        "ReleasedCount": 1,
        "ReleasedUser": [],
        "Reported": false,
        "SenderAddress": "sender@example.com",
        "Size": 14781,
        "SourceId": "",
        "Subject": "Check the inbox",
        "SystemReleased": false,
        "TagName": "testing_release",
        "TeamsConversationType": "",
        "Type": "High Confidence Phish"
    }
]
}

Human Readable Output

Results of ews-get-quarantinemessage

ApprovalId ApprovalUPN CustomData DeletedForRecipients Direction EntityType Expires Identity MessageId MoveToQuarantineAdminActionTakenBy MoveToQuarantineApprovalId Organization OverrideReason OverrideReasonIntValue PermissionToAllowSender PermissionToBlockSender PermissionToDelete PermissionToDownload PermissionToPreview PermissionToRelease PermissionToRequestRelease PermissionToViewHeader PolicyName PolicyType QuarantineTypes QuarantinedUser ReceivedTime RecipientAddress RecipientCount RecipientTag ReleaseStatus Released ReleasedBy ReleasedCount ReleasedUser Reported SenderAddress Size SourceId Subject SystemReleased TagName TeamsConversationType Type
        Outbound Email 2024-07-18T13:20:02.7166413+00:00 12345678-beef-dead-beef-0123456789ab\c0ffee13-beef-dead-beef-0123456789ab \u003c12345678-beef-dead-beef-0123456789ab@123456.789a.bcde.example.com\u003e     c0ffee13-beef-dead-beef-0123456789ab None 0 true false true true true true false false Default HostedContentFilterPolicy HighConfPhish [] 2024-07-02T13:20:02.7166413+00:00 [“admin@example.com”] 1 [””] NOTRELEASED false [] 0 [] false alerts@example.com 31218   Informational-severity alert: Tenant Allow/Block List entry is about to expire false AdminOnlyAccessPolicy   High Confidence Phish
        Inbound Email 2024-07-13T10:59:12.7581841+00:00 12345678-beef-dead-beef-0123456789ac\c0ffee13-beef-dead-beef-0123456789ac \u003c12345678-beef-dead-beef-0123456789ac@123456.789a.bcde.example.com\u003e     c0ffee13-beef-dead-beef-0123456789ac None 0 true false true true true true false false testing_quarantine_release HostedContentFilterPolicy HighConfPhish [] 2024-06-28T10:59:12.7581841+00:00 [“user@example.com”] 1 [””] RELEASED true [“SystemMailbox{deadbeef-dead-beef-dead-beefdeadbeef}@example.com”] 1 [] false sender@example.com 14781   Check the inbox false testing_release   High Confidence Phish

ews-release-quarantinemessage


Releases the quarantined messages. Uses the PowerShell Release-QuarantineMessage cmdlet.

Base Command


#### Input

| **Argument Name**      | **Description**                                            | **Required** |
|------------------------|------------------------------------------------------------|--------------|
| user                   | The email address of the user you want to release the quarantined message to.           | Optional |
| identities             | A comma-separated list of identities of the messages to release. | Optional |
| identity               | The identity of a single message to release.               | Optional |
| release_to_all         | Specify whether to release the message to all recipients.  | Optional |
| allow_sender           | Specify whether to allow the sender.                       | Optional |
| entity_type            | The entity workload type being released.                         | Optional |
| force                  | Specify whether to force the release.                      | Optional |
| report_false_positive  | Specify whether to report the message as a false positive. | Optional |
| action_type            | The action to perform on the quarantined message.     | Optional |

#### Context Output

There are no context outputs for this command.

#### Human Readable Output
>
>The message with identity 12345678-beef-dead-beef-0123456789ab\\c0ffee13-beef-dead-beef-0123456789ab has been sent for release from quarantine.

### ews-junk-rules-get

***
Gets junk rules for the specified mailbox.

#### Base Command

`ews-junk-rules-get`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| mailbox | ID of the mailbox for which to get junk rules. | Required |

#### Context Output

| **Path** | **Type** | **Description** |
| --- | --- | --- |
| EWS.Rule.Junk.BlockedSendersAndDomains | String | Blocked senders and domains list. |
| EWS.Rule.Junk.ContactsTrusted | Boolean | If true, contacts are trusted by default. |
| EWS.Rule.Junk.Email | String | Junk rule mailbox. |
| EWS.Rule.Junk.Enabled | Boolean | If true, junk rule is enabled. |
| EWS.Rule.Junk.Identity | String | Junk rule identity. |
| EWS.Rule.Junk.MailboxOwnerId | String | Mail box owner ID. |
| EWS.Rule.Junk.TrustedListsOnly | Boolean | If true, only a list defined in the trusted lists are trusted. |
| EWS.Rule.Junk.TrustedRecipientsAndDomains | String | List of trusted recipients and domains. |
| EWS.Rule.Junk.TrustedSendersAndDomains | String | List of trusted senders and domains. |

#### Command Example

```!ews-junk-rules-get mailbox="xsoar@dev.onmicrosoft.com"```

#### Context Example

```json
{
    "EWS": {
        "Rule": {
            "Junk": {
                "BlockedSendersAndDomains": [
                    "user1@gmail.com",
                    "user2@gmail.com"
                ],
                "ContactsTrusted": false,
                "Enabled": false,
                "Identity": "xsoar",
                "MailboxOwnerId": "xsoar",
                "TrustedListsOnly": false,
                "TrustedRecipientsAndDomains": [
                  "user1@gmail.com",
                  "user2@gmail.com"
                ],
                "TrustedSendersAndDomains": [
                  "user1@gmail.com",
                  "user2@gmail.com"
                ]
            }
        }
    }
}

Human Readable Output

EWS extension - ‘xsoar@dev.onmicrosoft.com’ Junk rules

BlockedSendersAndDomains ContactsTrusted Enabled TrustedListsOnly TrustedSendersAndDomains
[“user1@gmail.com”,”user2@gmail.com”] False False False [“user1@gmail.com”,”user2@gmail.com”]

ews-junk-rules-set


Sets junk rules for the specified mailbox.

Base Command

ews-junk-rules-set

Input

Argument Name Description Required
mailbox ID of the mailbox for which to set junk rules. Required
add_blocked_senders_and_domains Comma-separated list of blocked senders and domains to add to the mailbox. Optional
remove_blocked_senders_and_domains Comma-separated list of blocked senders and domains to remove from the mailbox. Optional
add_trusted_senders_and_domains Comma-separated list of trusted senders and domains to add to the mailbox. Optional
remove_trusted_senders_and_domains Comma-separated list of trusted senders and domains to remove from the mailbox. Optional
trusted_lists_only If true, trust only lists defined in the trusted lists. Can be “true” or “false”. Possible values are: true, false. Optional
contacts_trusted If true, contacts are trusted by default. Can be “true” or “false”. Possible values are: true, false. Optional
enabled If true, the junk rule is enabled. Can be “true” or “false”. Possible values are: true, false. Optional

Context Output

There is no context output for this command.

Command Example

!ews-junk-rules-set mailbox="xsoar@dev.onmicrosoft.com" add_blocked_senders_and_domains="test@gmail.com" add_trusted_senders_and_domains="dev.onmicrosoft.com"

Human Readable Output

EWS extension - ‘xsoar@dev.onmicrosoft.com’ Junk rules modified!

ews-global-junk-rules-set


Sets junk rules in all managed accounts.

Base Command

ews-global-junk-rules-set

Input

Argument Name Description Required
add_blocked_senders_and_domains Comma-separated list of blocked senders and domains to add to the mailbox. Optional
remove_blocked_senders_and_domains Comma-separated list of blocked senders and domains to remove from the mailbox. Optional
add_trusted_senders_and_domains Comma-separated list of trusted senders and domains to add to the mailbox. Optional
remove_trusted_senders_and_domains Comma-separated list of trusted senders and domains to remove from the mailbox. Optional
trusted_lists_only If true, trust only lists defined in the trusted lists. Can be “true” or “false”. Possible values are: true, false. Optional
contacts_trusted If true, contacts are trusted by default. Can be “true” or “false”. Possible values are: true, false. Optional
enabled If true, the junk rule is enabled. Can be “true” or “false”. Possible values are: true, false. Optional

Context Output

There is no context output for this command.

Command Example

!ews-global-junk-rules-set add_blocked_senders_and_domains="test@demisto.com" add_trusted_senders_and_domains="demisto.com"

Human Readable Output

EWS extension - Junk rules globally modified!

ews-message-trace-get


Searches message data for the last 10 days. If you run this command without any arguments, only data from the last 48 hours is returned.
If you enter a start date that is older than 10 days, you will receive an error and the command will return no results.
This command returns a maximum of 1,000,000 results, and will timeout on very large queries. If your query returns too many results, consider splitting it up using shorter start_date and end_date intervals.

Base Command

ews-message-trace-get

Input

Argument Name Description Required
sender_address The sender_address parameter filters the results by the sender’s email address. You can specify multiple values separated by commas.
.
Optional
recipient_address The recipient_address parameter filters the results by the recipient’s email address. You can specify multiple values separated by commas.
.
Optional
from_ip The from_ip parameter filters the results by the source IP address.
For incoming messages, the value of from_ip is the public IP address of the SMTP email server that sent the message.
For outgoing messages from Exchange Online, the value is blank.
.
Optional
to_ip The to_ip parameter filters the results by the destination IP address.
For outgoing messages, the value of to_ip is the public IP address in the resolved MX record for the destination domain.
For incoming messages to Exchange Online, the value is blank.
.
Optional
message_id The message_id parameter filters the results by the Message-ID header field of the message.
This value is also known as the Client ID. The format of the Message-ID depends on the messaging server that sent the message.
The value should be unique for each message. However, not all messaging servers create values for the Message-ID in the same way.
Be sure to include the full Message ID string (which may include angle brackets) and enclose the value in quotation marks (for example,”d9683b4c-127b-413a-ae2e-fa7dfb32c69d@DM3NAM06BG401.Eop-nam06.prod.protection.outlook.com”).
.
Optional
message_trace_id The message_trace_id parameter can be used with the recipient address to uniquely identify a message trace and obtain more details.
A message trace ID is generated for every message that’s processed by the system.
.
Optional
page The page number of the results you want to view.
Can be an integer between 1 and 1000. The default value is 1.
. Default is 1.
Optional
page_size The maximum number of entries per page.
Can be an integer between 1 and 5000. The default value is 100.
. Default is 100.
Optional
start_date The start date of the date range.
Use the short date format that’s defined in the Regional Options settings on the computer where you’re running the command. For example, if the computer is configured to use the short date format mm/dd/yyyy,
enter 09/01/2018 to specify September 1, 2018. You can enter the date only, or you can enter the date and time of day.
If you enter the date and time of day, enclose the value in quotation marks (“), for example, “09/01/2018 5:00 PM”.
Valid input for this parameter is from 10 days - now ago. The default value is 48 hours ago.
.
Optional
end_date The end date of the date range.
Use the short date format that’s defined in the Regional Options settings on the computer where you’re running the command.
For example, if the computer is configured to use the short date format mm/dd/yyyy, enter 09/01/2018 to specify September 1, 2018.
You can enter the date only, or you can enter the date and time of day.
If you enter the date and time of day, enclose the value in quotation marks (“), for example, “09/01/2018 5:00 PM”.
Valid input for this parameter is from start_date - now. The default value is now.
.
Optional
status The status of the message. Can be one of the following:
GettingStatus: The message is waiting for status update.
Failed: Message delivery was attempted and it failed or the message was filtered as spam or malware, or by transport rules.
Pending: Message delivery is underway or was deferred and is being retried.
Delivered: The message was delivered to its destination.
Expanded: There was no message delivery because the message was addressed to a distribution group and the membership of the distribution was expanded.
Quarantined: The message was quarantined.
* FilteredAsSpam: The message was marked as spam.
. Possible values are: GettingStatus, Failed, Pending, Delivered, Expanded, Quarantined, FilteredAsSpam.
Optional

Context Output

Path Type Description
EWS.MessageTrace.FromIP String The public IP address of the SMTP email server that sent the message.
EWS.MessageTrace.ToIP String The public IP address in the resolved MX record for the destination domain. For incoming messages to Exchange Online, the value is blank.
EWS.MessageTrace.Index Number Message index in pagination. (Index starts from 0)
EWS.MessageTrace.MessageId String Message-ID header field of the message.
EWS.MessageTrace.MessageTraceId String Message trace ID of the message.
EWS.MessageTrace.Organization String Message trace organization source.
EWS.MessageTrace.Received Date Message receive time.
EWS.MessageTrace.RecipientAddress String Message recipients address.
EWS.MessageTrace.SenderAddress String Message sender address.
EWS.MessageTrace.Size Number Message size in bytes.
EWS.MessageTrace.StartDate Date Message trace start date.
EWS.MessageTrace.EndDate Date Message trace end date.
EWS.MessageTrace.Status String Message status.
EWS.MessageTrace.Subject String Message subject.

Command Example


#### Context Example

```json
{
    "EWS": {
        "MessageTrace": [
            {
                "EndDate": "2021-01-03T06:14:14.9596257Z",
                "FromIP": "8.8.8.8",
                "Index": 1,
                "MessageId": "xxx",
                "MessageTraceId": "xxxx",
                "Organization": "dev.onmicrosoft.com",
                "Received": "2021-01-03T04:45:36.4662406",
                "RecipientAddress": "xsoar@dev.onmicrosoft.com",
                "SenderAddress": "xsoar@dev.onmicrosoft.com",
                "Size": 1882,
                "StartDate": "2021-01-01T06:14:14.9596257Z",
                "Status": "GettingStatus",
                "Subject": "Test mail",
                "ToIP": null
            },
            {
                "EndDate": "2021-01-03T06:15:14.9596257Z",
                "FromIP": "8.8.8.8",
                "Index": 2,
                "MessageId": "xxx",
                "MessageTraceId": "xxxx",
                "Organization": "dev.onmicrosoft.com",
                "Received": "2021-01-03T04:46:36.4662406",
                "RecipientAddress": "xsoar@dev.onmicrosoft.com",
                "SenderAddress": "xsoar@dev.onmicrosoft.com",
                "Size": 1882,
                "StartDate": "2021-01-01T06:15:14.9596257Z",
                "Status": "GettingStatus",
                "Subject": "Test mail",
                "ToIP": null
            }
        ]
    }
}

Human Readable Output

EWS extension - Messages trace

EndDate FromIP Index MessageId MessageTraceId Organization Received RecipientAddress SenderAddress Size StartDate Status Subject ToIP
1/3/2021 6:14:14 AM 8.8.8.8 0 xxx xxxx microsoft.com 1/3/2021 4:45:36 AM xsoar@dev.microsoft.com xsoar@dev.onmicrosoft.com 6975 1/1/2021 6:14:14 AM Delivered Test mail  
1/3/2021 6:15:14 AM 8.8.8.8 1 xxx xxxx microsoft.com 1/3/2021 4:46:36 AM xsoar@dev.microsoft.com xsoar@dev.onmicrosoft.com 6975 1/1/2021 6:15:14 AM Delivered Test mail  

ews-message-trace-list


You can use this command to search message data for the last 90 days. If you run this command without any arguments, only data from the last 48 hours is returned.
You can only return 10 days worth of data per query.
This command returns a maximum of 5,000 results. If your data exceeds the result size, consider splitting it up using shorter start_date and end_date intervals.
For information on how to use pagination, see the Pagination section below.

Pagination Information:
Pagination isn’t supported in this command due to API limitations. To query subsequent data, use the starting_recipient_address and end_date parameters with the values from the Recipient address and Received Time properties respectively of the previous result in the next query.
For more information, Click for the Microsoft API Documentation

Best Practices:

  • Use the limit argument to adjust the size of your results.
  • Be as precise as possible. Narrow the gap between start_date and end_date and use additional arguments (for example, starting_recipient_address) where possible.
  • Use message_id where possible (required for messages sent to more than 1000 recipients).

Base Command

ews-message-trace-list

Input

Argument Name Description Required
sender_address A comma-separated list of sender email addresses by which to filter the results. Optional
recipient_address A comma-separated list of recipient email addresses by which to filter the results. Optional
from_ip The source IP address used to filter results. For incoming messages, from_ip is the public IP of the SMTP server that sent the message. For outgoing messages from Exchange Online, the value is blank. Optional
to_ip The destination IP address used to filter results. For outgoing messages, the to_ip value is the public IP address in the resolved MX record for the destination domain. For incoming messages to Exchange Online, this value is blank. Optional
message_id A comma-separated list of Message-ID header fields used to filter results. This value is also known as the Client ID. The format of the Message-ID depends on the messaging server that sent the message and should be unique for each message. However, not all servers generate Message-ID values in the same way. Include the full Message-ID string (which may contain angle brackets) and enclose each value in quotation marks. Optional
message_trace_id The message trace ID used with the recipient address to uniquely identify a message trace and obtain more details. A message trace ID is generated for every message that’s processed by the system. Optional
start_date The start date of the date range. Use the short date format that’s defined in the Regional Options settings on the computer where you’re running the command. For example, if the computer is configured to use the short date format mm/dd/yyyy, enter 09/01/2018 to specify September 1, 2018. You can enter the date only, or you can enter the date and time of day. If you enter the date and time of day, enclose the value in quotation marks (“), for example, “09/01/2018 5:00 PM”. Valid input for this parameter is from 90 days ago until now. Default is 48 hours ago. Optional
end_date The end date of the date range. Use the short date format that’s defined in the Regional Options settings on the computer where you’re running the command. For example, if the computer is configured to use the short date format mm/dd/yyyy, enter 09/01/2018 to specify September 1, 2018. You can enter the date and time of day. If you enter the date and time of day, enclose the value in quotation marks (“), for example, “09/01/2018 5:00 PM”. Valid input for this parameter is from the start_date - now. Default is now. Optional
status A comma-separated list of message statuses by which to filter the results. Can be one of the following: GettingStatus (The message is waiting for status update), Failed (Message delivery was attempted and it failed or the message was filtered as spam or malware, or by transport rules), Pending (Message delivery is underway or was deferred and is being retried), Delivered (The message was delivered to its destination), Expanded (There was no message delivery because the message was addressed to a distribution group and the membership of the distribution was expanded), Quarantined (The message was quarantined), FilteredAsSpam (The message was marked as spam). Possible values are: GettingStatus, Failed, Pending, Delivered, Expanded, Quarantined, FilteredAsSpam. Optional
subject The subject parameter filters the results by the subject of the message. If the value contains spaces, enclose the value in quotation marks (“). Optional
subject_filter_type The subject_filter_type parameter specifies how the value of the subject parameter is evaluated. Valid values are: Contains, EndsWith, StartsWith. It is recommended to use StartsWith or EndsWith instead of Contains whenever possible. Optional
starting_recipient_address The starting_recipient_address parameter is used with the end_date parameter to query subsequent data while avoiding duplicates. For subsequent queries, use the Recipient address and Received Time from the last record of the previous results as the values for starting_recipient_address and end_date, respectively. Optional
limit The maximum number of results to return. A valid value is from 1 to 5000. The default value is 1000. Optional

Context Output

Path Type Description
EWS.MessageTrace.FromIP String The public IP address of the SMTP email server that sent the message.
EWS.MessageTrace.ToIP String The public IP address in the resolved MX record for the destination domain. For incoming messages to Exchange Online, the value is blank.
EWS.MessageTrace.MessageId String Message-ID header field of the message.
EWS.MessageTrace.MessageTraceId String Message trace ID of the message.
EWS.MessageTrace.Received Date Message receive time.
EWS.MessageTrace.RecipientAddress String Message recipients address.
EWS.MessageTrace.SenderAddress String Message sender address.
EWS.MessageTrace.Size Number Message size in bytes.
EWS.MessageTrace.Status String Message status.
EWS.MessageTrace.Subject String Message subject.

Command Example


#### Context Example

```json
{
"EWS": {
 "MessageTrace": [
            {
                "EndDate": "2021-01-03T06:14:14.9596257Z",
                "FromIP": "8.8.8.8",
                "Index": 1,
                "MessageId": "xxx",
                "MessageTraceId": "xxxx",
                "Organization": "dev.onmicrosoft.com",
                "Received": "2021-01-03T04:45:36.4662406",
                "RecipientAddress": "xsoar@dev.onmicrosoft.com",
                "SenderAddress": "xsoar@dev.onmicrosoft.com",
                "Size": 1882,
                "StartDate": "2021-01-01T06:14:14.9596257Z",
                "Status": "GettingStatus",
                "Subject": "Test mail",
                "ToIP": null
            },
            {
                "EndDate": "2021-01-03T06:15:14.9596257Z",
                "FromIP": "8.8.8.8",
                "Index": 2,
                "MessageId": "xxx",
                "MessageTraceId": "xxxx",
                "Organization": "dev.onmicrosoft.com",
                "Received": "2021-01-03T04:46:36.4662406",
                "RecipientAddress": "xsoar@dev.onmicrosoft.com",
                "SenderAddress": "xsoar@dev.onmicrosoft.com",
                "Size": 1882,
                "StartDate": "2021-01-01T06:15:14.9596257Z",
                "Status": "GettingStatus",
                "Subject": "Test mail",
                "ToIP": null
            }
        ]
    }
}

Human Readable Output

EWS extension - Messages trace

EndDate FromIP Index MessageId MessageTraceId Organization Received RecipientAddress SenderAddress Size StartDate Status Subject ToIP
1/3/2021 6:14:14 AM 8.8.8.8 0 xxx xxxx microsoft.com 1/3/2021 4:45:36 AM xsoar@dev.microsoft.com xsoar@dev.onmicrosoft.com 6975 1/1/2021 6:14:14 AM Delivered Test mail  
1/3/2021 6:15:14 AM 8.8.8.8 1 xxx xxxx microsoft.com 1/3/2021 4:46:36 AM xsoar@dev.microsoft.com xsoar@dev.onmicrosoft.com 6975 1/1/2021 6:15:14 AM Delivered Test mail  

ews-federation-trust-get


Displays the federation trust configured for the Exchange organization.

Base Command

ews-federation-trust-get

Input

Argument Name Description Required
domain_controller The domain controller identified by its fully qualified domain name (FQDN). For example, dc01.example.com. This argument is available only in on-premises Exchange. Optional
identity The federation trust ID. If not specified, the command returns all federation trusts configured for the Exchange organization. Optional

Context Output

Path Type Description
EWS.FederationTrust.AdminDisplayName String Administrator display name of the federation trust.
EWS.FederationTrust.ApplicationIdentifier String Application identifier of the federation trust.
EWS.FederationTrust.ApplicationUri String Application URI of the federation trust.
EWS.FederationTrust.DistinguishedName String Distinguished name of the federation trust.
EWS.FederationTrust.ExchangeObjectId String Exchange object ID of the federation trust.
EWS.FederationTrust.ExchangeVersion String Exchange version of the federation trust.
EWS.FederationTrust.Guid String GUID of the federation trust.
EWS.FederationTrust.Id String ID of the federation trust.
EWS.FederationTrust.Identity String Identity of the federation trust.
EWS.FederationTrust.IsValid Boolean Whether the federation trust is valid.
EWS.FederationTrust.MetadataEpr String Metadata EPR of the federation trust.
EWS.FederationTrust.MetadataPollInterval Date Metadata poll interval of the federation trust.
EWS.FederationTrust.MetadataPutEpr Unknown Metadata put EPR of the federation trust.
EWS.FederationTrust.Name String Name of the federation trust.
EWS.FederationTrust.NamespaceProvisioner String Namespace provisioner of the federation trust.
EWS.FederationTrust.ObjectCategory String Object category of the federation trust.
EWS.FederationTrust.ObjectClass String Object class of the federation trust.
EWS.FederationTrust.ObjectState String Object state of the federation trust.
EWS.FederationTrust.OrgCertificate.Archived Boolean Whether the organization certificate of the federation trust is archived.
EWS.FederationTrust.OrgCertificate.Extensions.Critical Boolean Whether the extensions of the organization certificate are critical.
EWS.FederationTrust.OrgCertificate.Extensions.Oid.FriendlyName String Friendly name of the OID of the organization certificate extensions.
EWS.FederationTrust.OrgCertificate.Extensions.Oid.Value String Value of the OID of the organization certificate extensions.
EWS.FederationTrust.OrgCertificate.Extensions.RawData Number Raw data of the organization certificate extensions.
EWS.FederationTrust.OrgCertificate.Extensions.SubjectKeyIdentifier String Subject key identifier of the organization certificate extensions.
EWS.FederationTrust.OrgCertificate.Extensions.KeyUsages Number Key usages of the organization certificate extensions.
EWS.FederationTrust.OrgCertificate.Extensions.EnhancedKeyUsages.FriendlyName String Friendly name of the enhanced key usages of the organization certificate extensions.
EWS.FederationTrust.OrgCertificate.Extensions.EnhancedKeyUsages.Value String Value of the enhanced key usages of the organization certificate extensions.
EWS.FederationTrust.OrgCertificate.Extensions.CertificateAuthority Boolean Whether the organization certificate extensions have a certificate authority.
EWS.FederationTrust.OrgCertificate.Extensions.HasPathLengthConstraint Boolean Whether the organization certificate extensions have a path length constraint.
EWS.FederationTrust.OrgCertificate.Extensions.PathLengthConstraint Number Path length constraint of the organization certificate extensions.
EWS.FederationTrust.OrgCertificate.FriendlyName String Friendly name of the organization certificate.
EWS.FederationTrust.OrgCertificate.Handle.value Number The handle value of the organization certificate.
EWS.FederationTrust.OrgCertificate.HasPrivateKey Boolean Whether the organization certificate has a private key.
EWS.FederationTrust.OrgCertificate.Issuer String Issuer of the organization certificate.
EWS.FederationTrust.OrgCertificate.IssuerName.Name String Name of the issuer of the organization certificate.
EWS.FederationTrust.OrgCertificate.IssuerName.Oid.FriendlyName Unknown Friendly name of the OID of the issuer name of the organization certificate.
EWS.FederationTrust.OrgCertificate.IssuerName.Oid.Value Unknown Value of the OID of the issuer name of the organization certificate.
EWS.FederationTrust.OrgCertificate.IssuerName.RawData Number Raw Data of the issuer name of the organization certificate.
EWS.FederationTrust.OrgCertificate.NotAfter Date The date until when the organization certificate is valid.
EWS.FederationTrust.OrgCertificate.NotBefore Date The date the organization certificate became valid.
EWS.FederationTrust.OrgCertificate.PrivateKey Unknown Private key of the organization certificate.
EWS.FederationTrust.OrgCertificate.PublicKey.EncodedKeyValue.Oid.FriendlyName String Friendly name of the OID of the encoded key value of the public key of the organization certificate.
EWS.FederationTrust.OrgCertificate.PublicKey.EncodedKeyValue.Oid.Value String Value of the OID of the encoded key value of the public key of the organization certificate.
EWS.FederationTrust.OrgCertificate.PublicKey.EncodedKeyValue.RawData Number Raw data of the encoded key value of the public key of the organization certificate.
EWS.FederationTrust.OrgCertificate.PublicKey.EncodedParameters.Oid.FriendlyName String Friendly name of the OID of the encoded parameters of the public key of the organization certificate.
EWS.FederationTrust.OrgCertificate.PublicKey.EncodedParameters.Oid.Value String Value of the OID of the encoded parameters of the public key of the organization certificate.
EWS.FederationTrust.OrgCertificate.PublicKey.EncodedParameters.RawData Number Raw Data of the encoded parameters of the public key of the organization certificate.
EWS.FederationTrust.OrgCertificate.PublicKey.Key.KeyExchangeAlgorithm String Key exchange algorithm of the public key of the organization certificate.
EWS.FederationTrust.OrgCertificate.PublicKey.Key.LegalKeySizes.MaxSize Number Maximum size of the public key of the organization certificate.
EWS.FederationTrust.OrgCertificate.PublicKey.Key.LegalKeySizes.MinSize Number Minimum size of the public key of the organization certificate.
EWS.FederationTrust.OrgCertificate.PublicKey.Key.LegalKeySizes.SkipSize Number SkiPSize of the public key of the organization certificate.
EWS.FederationTrust.OrgCertificate.PublicKey.Key.SignatureAlgorithm String Signature algorithm of the public key of the organization certificate.
EWS.FederationTrust.OrgCertificate.PublicKey.Oid.FriendlyName String Friendly name of the OID of the public key of the organization certificate.
EWS.FederationTrust.OrgCertificate.PublicKey.Oid.Value String Value of the OID of the public key of the organization certificate.
EWS.FederationTrust.OrgCertificate.RawData Number Raw data of the organization certificate.
EWS.FederationTrust.OrgCertificate.SerialNumber String Serial number of the organization certificate.
EWS.FederationTrust.OrgCertificate.SignatureAlgorithm.FriendlyName String Friendly name of the signature algorithm of the organization certificate.
EWS.FederationTrust.OrgCertificate.SignatureAlgorithm.Value String Value of the signature algorithm of the organization certificate.
EWS.FederationTrust.OrgCertificate.Subject String Subject of the organization certificate.
EWS.FederationTrust.OrgCertificate.SubjectName.Name String Name of the subject of the organization certificate.
EWS.FederationTrust.OrgCertificate.SubjectName.Oid.FriendlyName Unknown Friendly name of the OID of the subject of the organization certificate.
EWS.FederationTrust.OrgCertificate.SubjectName.Oid.Value Unknown Value of the OID of the subject name of the organization certificate.
EWS.FederationTrust.OrgCertificate.SubjectName.RawData Number Raw data of the subject name of the organization certificate.
EWS.FederationTrust.OrgCertificate.Thumbprint String Thumbprint of the organization certificate.
EWS.FederationTrust.OrgCertificate.Version Number Version of the organization certificate.
EWS.FederationTrust.OrgNextCertificate Unknown Next organization certificate.
EWS.FederationTrust.OrgNextPrivCertificate String Next organization private certificate.
EWS.FederationTrust.OrgPrevCertificate.Archived Boolean Whether to archive the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.Extensions.Critical Boolean Whether the extensions of the previous organization certificate are critical.
EWS.FederationTrust.OrgPrevCertificate.Extensions.Oid.FriendlyName String Friendly name of the OID of the previous organization certificate extensions.
EWS.FederationTrust.OrgPrevCertificate.Extensions.Oid.Value String Value of the OID of the previous organization certificate extensions.
EWS.FederationTrust.OrgPrevCertificate.Extensions.RawData Number Raw data of the previous organization certificate extensions.
EWS.FederationTrust.OrgPrevCertificate.Extensions.SubjectKeyIdentifier String Subject key identifier of the previous organization certificate extensions.
EWS.FederationTrust.OrgPrevCertificate.Extensions.KeyUsages Number Key usages of the previous organization certificate extensions.
EWS.FederationTrust.OrgPrevCertificate.Extensions.EnhancedKeyUsages.FriendlyName String Friendly name of the enhanced key usages of the previous organization certificate extensions.
EWS.FederationTrust.OrgPrevCertificate.Extensions.EnhancedKeyUsages.Value String Value of the enhanced key usages of the previous organization certificate extensions.
EWS.FederationTrust.OrgPrevCertificate.FriendlyName String Friendly name of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.Handle.value Number Value of the handle of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.HasPrivateKey Boolean Whether the previous organization certificate has a private key.
EWS.FederationTrust.OrgPrevCertificate.Issuer String Issuer of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.IssuerName.Name String Name of the issuer of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.IssuerName.Oid.FriendlyName Unknown Friendly name of the OID of the issuer of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.IssuerName.Oid.Value Unknown Value of the OID of the issuer of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.IssuerName.RawData Number Raw Data of the issuer of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.NotAfter Date The date until when the previous organization certificate is valid.
EWS.FederationTrust.OrgPrevCertificate.NotBefore Date The date the previous organization certificate became valid.
EWS.FederationTrust.OrgPrevCertificate.PrivateKey Unknown Private Key of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.PublicKey.EncodedKeyValue.Oid.FriendlyName String Friendly name of the OID of the encoded key value of the public key of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.PublicKey.EncodedKeyValue.Oid.Value String Value of the OID of the encoded key value of the public key of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.PublicKey.EncodedKeyValue.RawData Number Raw data of the encoded key value of the public key of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.PublicKey.EncodedParameters.Oid.FriendlyName String Friendly name of the OID of the encoded parameters of the public key of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.PublicKey.EncodedParameters.Oid.Value String Value of the OID of the encoded parameters of the public key of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.PublicKey.EncodedParameters.RawData Number Raw data of the encoded parameters of the public key of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.PublicKey.Key.KeyExchangeAlgorithm String Key exchange algorithm of the public key of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.PublicKey.Key.LegalKeySizes.MaxSize Number Maximum size of the public key of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.PublicKey.Key.LegalKeySizes.MinSize Number Minimum size of the public key of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.PublicKey.Key.LegalKeySizes.SkipSize Number SkiPSize of the public key of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.PublicKey.Key.SignatureAlgorithm String Signature algorithm of the public key of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.PublicKey.Oid.FriendlyName String Friendly Name of the OID of the public key of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.PublicKey.Oid.Value String Value of the OID of the public key of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.RawData Number Raw Data of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.SerialNumber String Serial number of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.SignatureAlgorithm.FriendlyName String Friendly name of the signature algorithm of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.SignatureAlgorithm.Value String Value of the signature algorithm of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.Subject String Subject of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.SubjectName.Name String Name of the subject of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.SubjectName.Oid.FriendlyName Unknown Friendly name of the OID of the subject of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.SubjectName.Oid.Value Unknown Value of the OID of the subject name of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.SubjectName.RawData Number Raw data of the subject name of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.Thumbprint String Thumbprint of the previous organization certificate.
EWS.FederationTrust.OrgPrevCertificate.Version Number Version of the previous organization certificate.
EWS.FederationTrust.OrgPrevPrivCertificate String Organization previous private certificate.
EWS.FederationTrust.OrgPrivCertificate String Organization private certificate.
EWS.FederationTrust.OrganizationId String Organization ID.
EWS.FederationTrust.OriginatingServer String Originating server.
EWS.FederationTrust.PSComputerName String PowerShell computer name.
EWS.FederationTrust.PSShowComputerName Boolean Whether to show the PowerShell computer name.
EWS.FederationTrust.PolicyReferenceUri String Policy Reference URI.
EWS.FederationTrust.RunspaceId String Runspace ID.
EWS.FederationTrust.TimesOfUnmatchPartner Number Times Of unmatch partner.
EWS.FederationTrust.TokenIssuerCertReference String Token issuer certificate reference.
EWS.FederationTrust.TokenIssuerCertificate.Archived Boolean Whether the token issuer certificate is archived.
EWS.FederationTrust.TokenIssuerCertificate.Extensions.Critical Boolean Whether the extensions of the token issuer certificate are critical.
EWS.FederationTrust.TokenIssuerCertificate.Extensions.Oid.FriendlyName String Friendly name of the OID of the extensions of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.Extensions.Oid.Value String Value of the OID of the extensions of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.Extensions.RawData Number Raw Data of the extensions of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.Extensions.SubjectKeyIdentifier String Subject key identifier of the extensions of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.Extensions.KeyUsages Number Key usages of the extensions of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.FriendlyName String Friendly name of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.Handle.value Number Value of the handle of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.HasPrivateKey Boolean Whether the token issuer certificate has a private key.
EWS.FederationTrust.TokenIssuerCertificate.Issuer String Issuer of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.IssuerName.Name String Name of the issuer of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.IssuerName.Oid.FriendlyName Unknown Friendly name of the OID of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.IssuerName.Oid.Value Unknown Value of the OID of the issuer of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.IssuerName.RawData Number Raw data of the issuer of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.NotAfter Date The date until when the token issuer certificate is valid.
EWS.FederationTrust.TokenIssuerCertificate.NotBefore Date The date the token issuer certificate became valid.
EWS.FederationTrust.TokenIssuerCertificate.PrivateKey Unknown Private key of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.PublicKey.EncodedKeyValue.Oid.FriendlyName String Friendly name of the OID of the encoded key value of the public key of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.PublicKey.EncodedKeyValue.Oid.Value String Value of the OID of the encoded key value of the public key of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.PublicKey.EncodedKeyValue.RawData Number Raw data of the encoded key value of the public key of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.PublicKey.EncodedParameters.Oid.FriendlyName String Friendly name of the OID of the encoded parameters of the public key of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.PublicKey.EncodedParameters.Oid.Value String Value of the OID of the encoded parameters of the public key of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.PublicKey.EncodedParameters.RawData Number Raw Data of the encoded parameters of the public key of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.PublicKey.Key.KeyExchangeAlgorithm String Key exchange algorithm of the public key of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.PublicKey.Key.LegalKeySizes.MaxSize Number Maximum size of the public key of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.PublicKey.Key.LegalKeySizes.MinSize Number Minimum size of the public key of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.PublicKey.Key.LegalKeySizes.SkipSize Number SkiPSize of the public key of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.PublicKey.Key.SignatureAlgorithm String Signature algorithm of the public key of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.PublicKey.Oid.FriendlyName String Friendly name of the OID of the public key of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.PublicKey.Oid.Value String Value of the OID of the public key of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.RawData Number Raw Data of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.SerialNumber String Serial number of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.SignatureAlgorithm.FriendlyName String Friendly name of the signature algorithm of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.SignatureAlgorithm.Value String Value of the signature algorithm of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.Subject String Subject of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.SubjectName.Name String Name of the subject of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.SubjectName.Oid.FriendlyName Unknown Friendly name of the OID of the subject of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.SubjectName.Oid.Value Unknown Value of the OID of the subject of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.SubjectName.RawData Number Raw data of the subject of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.Thumbprint String Thumbprint of the token issuer certificate.
EWS.FederationTrust.TokenIssuerCertificate.Version Number Version of the token issuer certificate.
EWS.FederationTrust.TokenIssuerEpr String Token issuer EPR.
EWS.FederationTrust.TokenIssuerMetadataEpr String Token issuer metadata EPR.
EWS.FederationTrust.TokenIssuerPrevCertReference String Token issuer previous certificate reference.
EWS.FederationTrust.TokenIssuerPrevCertificate.Archived Boolean Whether the token issuer previous certificate was archived.
EWS.FederationTrust.TokenIssuerPrevCertificate.Extensions.Critical Boolean Whether the extensions of the token issuer previous certificate was critical.
EWS.FederationTrust.TokenIssuerPrevCertificate.Extensions.Oid.FriendlyName String Friendly name of the OID of the extensions of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.Extensions.Oid.Value String Value of the OID of the extensions of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.Extensions.RawData Number Raw data of the extensions of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.Extensions.SubjectKeyIdentifier String Subject key identifier of the extensions of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.Extensions.KeyUsages Number Key usages of the extensions of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.FriendlyName String Friendly name of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.Handle.value Number The handle value of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.HasPrivateKey Boolean Whether the token issuer previous certificate has a private key.
EWS.FederationTrust.TokenIssuerPrevCertificate.Issuer String Issuer of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.IssuerName.Name String Name of the issuer of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.IssuerName.Oid.FriendlyName Unknown Friendly name of the OID of the issuer name of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.IssuerName.Oid.Value Unknown Value of the OID of the issuer name of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.IssuerName.RawData Number Raw Data of the issuer name of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.NotAfter Date The date until when the token issuer previous certificate is valid.
EWS.FederationTrust.TokenIssuerPrevCertificate.NotBefore Date The date the token issuer previous certificate became valid.
EWS.FederationTrust.TokenIssuerPrevCertificate.PrivateKey Unknown Private Key of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.PublicKey.EncodedKeyValue.Oid.FriendlyName String Friendly name of the OID of the encoded key value of the public key of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.PublicKey.EncodedKeyValue.Oid.Value String Value of the OID of the encoded key value of the public key of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.PublicKey.EncodedKeyValue.RawData Number Raw data of the encoded key value of the public key of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.PublicKey.EncodedParameters.Oid.FriendlyName String Friendly name of the OID of the encoded parameters of the public key of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.PublicKey.EncodedParameters.Oid.Value String Value of the OID of the encoded parameters of the public key of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.PublicKey.EncodedParameters.RawData Number Raw data of the encoded parameters of the public key of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.PublicKey.Key.KeyExchangeAlgorithm String Key exchange algorithm of the public key of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.PublicKey.Key.LegalKeySizes.MaxSize Number Maximum size of the public key of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.PublicKey.Key.LegalKeySizes.MinSize Number Minimum size of the public key of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.PublicKey.Key.LegalKeySizes.SkipSize Number SkiPSize of the public key of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.PublicKey.Key.SignatureAlgorithm String Signature algorithm of the public key of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.PublicKey.Oid.FriendlyName String Friendly Name of the OID of the public key of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.PublicKey.Oid.Value String Value of the OID of teh public key of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.RawData Number Raw Data of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.SerialNumber String Serial number of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.SignatureAlgorithm.FriendlyName String Friendly name of the signature algorithm of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.SignatureAlgorithm.Value String Value of the signature algorithm of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.Subject String Subject of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.SubjectName.Name String Name of the subject of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.SubjectName.Oid.FriendlyName Unknown Friendly Name of the OID of the subject of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.SubjectName.Oid.Value Unknown Value of the OID of the subject name of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.SubjectName.RawData Number Raw data of the subject name of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.Thumbprint String Thumbprint of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerPrevCertificate.Version Number Version of the token issuer previous certificate.
EWS.FederationTrust.TokenIssuerType String Token issuer type of the federation trust.
EWS.FederationTrust.TokenIssuerUri String Token Issuer UIR of the federation trust.
EWS.FederationTrust.WebRequestorRedirectEpr String Web requestor redirect EPR of the federation trust.
EWS.FederationTrust.WhenChanged Date The date the federation trust was changed.
EWS.FederationTrust.WhenChangedUTC Date The date in UTC format of when the federation trust was changed.
EWS.FederationTrust.WhenCreated Date The date the federation trust was created.
EWS.FederationTrust.WhenCreatedUTC Date The date in UTC format of when the federation trust was created.

ews-federation-configuration-get


Retrieves the Exchange organization’s federated organization identifier and related details, such as federated domains, organization contact, and status.

Base Command

ews-federation-configuration-get

Input

Argument Name Description Required
domain_controller The fully qualified domain name (FQDN) of the domain controller. For example, dc01.example.com. This argument is available only in on-premises Exchange. Optional
identity The federation trust ID. If not specified, all federation trusts configured for the Exchange organization are returned. Optional
include_extended_domain_info The IncludeExtendedDomainInfo switch specifies that the command query Microsoft Federation Gateway for the status of each accepted domain that’s federated. The status is returned with each domain in the Domains property. Possible values: “true” and “false”. Possible values are: true, false. Default is false. Optional

Context Output

Path Type Description
EWS.FederationConfiguration.AccountNamespace String Account namespace of the federation configuration.
EWS.FederationConfiguration.DefaultDomain Unknown Default domain of the federation configuration.
EWS.FederationConfiguration.DelegationTrustLink String Delegation trust link of the federation configuration.
EWS.FederationConfiguration.DistinguishedName String Distinguished name of the federation configuration.
EWS.FederationConfiguration.Domains String Domains of the federation configuration.
EWS.FederationConfiguration.Enabled Boolean Whether the federation configuration is enabled.
EWS.FederationConfiguration.ExchangeObjectId String Exchange object ID of the federation configuration.
EWS.FederationConfiguration.ExchangeVersion String Exchange version of the federation configuration.
EWS.FederationConfiguration.Guid String GUID of the federation configuration.
EWS.FederationConfiguration.Id String ID of the federation configuration.
EWS.FederationConfiguration.Identity String Identity of the federation configuration.
EWS.FederationConfiguration.IsValid Boolean Whether the federation configration is valid.
EWS.FederationConfiguration.Name String Name of the federation configuration.
EWS.FederationConfiguration.ObjectCategory String Object category of the federation configuration.
EWS.FederationConfiguration.ObjectClass String Object class of the federation configuration.
EWS.FederationConfiguration.ObjectState String Object state of the federation configuration.
EWS.FederationConfiguration.OrganizationContact String Organization contact of the federation configuration.
EWS.FederationConfiguration.OrganizationId String Organization ID of the federation configuration.
EWS.FederationConfiguration.OriginatingServer String Originating server of the federation configuration.
EWS.FederationConfiguration.PSComputerName String PowerShell computer name of the federation configuration.
EWS.FederationConfiguration.PSShowComputerName Boolean Whether to show the PowerShell computer name of the federation configuration.
EWS.FederationConfiguration.RunspaceId String Runspace ID of the federation configuration.
EWS.FederationConfiguration.WhenChanged Date The date the federation configuration was changed.
EWS.FederationConfiguration.WhenChangedUTC Date The date in UTC format of when the federation configuration was changed.
EWS.FederationConfiguration.WhenCreated Date The date the federation configuration was created.
EWS.FederationConfiguration.WhenCreatedUTC Date The date in UTC format of when the federation configuration was created.

ews-remote-domain-get


Gets the configuration information for the remote domains configured in your organization. This command is available only in the Exchange Online PowerShell V3 module.

Base Command

ews-remote-domain-get

Input

Argument Name Description Required
domain_controller The fully qualified domain name (FQDN) of the domain controller. For example, dc01.example.com.
This argument is available only in on-premises Exchange.
Optional
identity The remote domain that you want to view. You can use the GUID, ID, or any other identifier. Optional

Context Output

Path Type Description
EWS.RemoteDomain.AdminDisplayName String Admin display name of the remote domain.
EWS.RemoteDomain.AllowedOOFType String Allowed OOF type of the remote domain.
EWS.RemoteDomain.AutoForwardEnabled Boolean Whether auto forward is enabled for the remote domain.
EWS.RemoteDomain.AutoReplyEnabled Boolean Whether auto reply is enabled for the remote domain..
EWS.RemoteDomain.ByteEncoderTypeFor7BitCharsets String Byte encoder type For 7-bit charsets of the remote domain.
EWS.RemoteDomain.CharacterSet String Character set of the remote domain.
EWS.RemoteDomain.ContentType String Content type of the remote domain.
EWS.RemoteDomain.DeliveryReportEnabled Boolean Whether delivery report is enabled for the remote domain.
EWS.RemoteDomain.DisplaySenderName Boolean Whether to display the sender name for the remote domain.
EWS.RemoteDomain.DistinguishedName String Distinguished name of the remote domain.
EWS.RemoteDomain.DomainName String Domain name of the remote domain.
EWS.RemoteDomain.ExchangeObjectId String Exchange object ID of the remote domain.
EWS.RemoteDomain.ExchangeVersion String Exchange version of the remote domain.
EWS.RemoteDomain.Guid String GUID of the remote domain.
EWS.RemoteDomain.Id String ID of the remote domain.
EWS.RemoteDomain.Identity String Identity of the remote domain.
EWS.RemoteDomain.IsInternal Boolean Whether the remote domain is internal.
EWS.RemoteDomain.IsValid Boolean Whether the remote domain is valid.
EWS.RemoteDomain.LineWrapSize String Line wrap size for the remote domain.
EWS.RemoteDomain.MeetingForwardNotificationEnabled Boolean Whether meeting forward notification is enabled for the remote domain.
EWS.RemoteDomain.MessageCountThreshold Number Message count threshold of the remote domain.
EWS.RemoteDomain.NDRDiagnosticInfoEnabled Boolean Whether NDR diagnostic information is enabled for the remote domain.
EWS.RemoteDomain.NDREnabled Boolean Whether NDR is enabled for the remote domain.
EWS.RemoteDomain.Name String Name of the remote domain.
EWS.RemoteDomain.NonMimeCharacterSet String Non-mime character set of the remote domain.
EWS.RemoteDomain.ObjectCategory String Object category of the remote domain.
EWS.RemoteDomain.ObjectClass String Object class of the remote domain.
EWS.RemoteDomain.ObjectState String Object state of the remote domain.
EWS.RemoteDomain.OrganizationId String Organization ID of the remote domain.
EWS.RemoteDomain.OriginatingServer String Originating server of the remote domain.
EWS.RemoteDomain.PSComputerName String PowerShell computer name of the remote domain.
EWS.RemoteDomain.PSShowComputerName Boolean Whether to show the PowerShell computer name for the remote domain.
EWS.RemoteDomain.PreferredInternetCodePageForShiftJis String Preferred internet code page for shift JIS for the remote domain.
EWS.RemoteDomain.RequiredCharsetCoverage Unknown Required charset coverage for the remote domain.
EWS.RemoteDomain.RunspaceId String Runspace ID for the remote domain.
EWS.RemoteDomain.TNEFEnabled Unknown Whether TNEF is enabled for the remote domain.
EWS.RemoteDomain.TargetDeliveryDomain Boolean Whether the remote domain is used for the target email address of mail users that represent the users in the other forest.
EWS.RemoteDomain.TrustedMailInboundEnabled Boolean Whether inbound trusted mail is enabled.
EWS.RemoteDomain.TrustedMailOutboundEnabled Boolean Whether outbound trusted mail is enabled.
EWS.RemoteDomain.UseSimpleDisplayName Boolean Whether to use the simple display name.
EWS.RemoteDomain.WhenChanged Date The date the remote domain was changed.
EWS.RemoteDomain.WhenChangedUTC Date The date in UTC format of when the remote domain was changed.
EWS.RemoteDomain.WhenCreated Date The date the remote domain was created.
EWS.RemoteDomain.WhenCreatedUTC Date The date in UTC format of when the remote domain was created.

ews-user-list


Displays the existing user objects in your organization.

Base Command

ews-user-list

Input

Argument Name Description Required
identity The mailbox you want to view. Optional
organizational_unit The object’s location in Active Directory by which to filter the results. Optional
limit Maximum number of users to get. A value of 0 means to get all users. Default is 10. Optional

Context Output

Path Type Description
EWS.User.AccountDisabled Boolean Whether the user account is disabled.
EWS.User.AllowUMCallsFromNonUsers Boolean Whether to allow Unified Messaging calls from non-users.
EWS.User.ArchiveRelease String The archive release of the user object.
EWS.User.AssistantName String The assistant name of the user object.
EWS.User.AuthenticationPolicy Unknown The authentication policy of the user object.
EWS.User.CanHaveCloudCache Boolean Whether the user object can have cloud cache.
EWS.User.City String The city of the user object.
EWS.User.CloudCacheAccountType String Cloud cache account type of the user object.
EWS.User.CloudCacheProvider Number Cloud cache provider of the user object.
EWS.User.CloudCacheRemoteEmailAddress String Cloud cache remote email address of the user object.
EWS.User.CloudCacheScope Number Cloud cache scope of the user object.
EWS.User.CloudCacheUserName String Cloud cache user name of the user object.
EWS.User.Company String Company of the user object.
EWS.User.ConsumerNetID Unknown Consumer net ID of the user object.
EWS.User.CountryOrRegion String Country or region of the .
EWS.User.DefaultMailboxWorkloadsMask Unknown Default mailbox workloads mask of the user object.
EWS.User.Department String Department of the user object.
EWS.User.DesiredMailboxWorkloads Unknown Desired mailbox workloads of the user object.
EWS.User.DesiredMailboxWorkloadsGracePeriod Unknown Desired mailbox workloads grace period of the user object.
EWS.User.DesiredMailboxWorkloadsModified Unknown Modified desired mailbox workloads of the user object.
EWS.User.DisplayName String Display name of the user object.
EWS.User.DistinguishedName String Distinguished name of the user object.
EWS.User.ExchangeObjectId String Exchange object ID of the user object.
EWS.User.ExchangeVersion String Exchange version of the user object.
EWS.User.ExternalDirectoryObjectId String External Directory Object ID of the user object.
EWS.User.Fax String Fax of the user object.
EWS.User.FirstName String First name of the user object.
EWS.User.GeoCoordinates Unknown Geo coordinates of the user object.
EWS.User.Guid String GUID of the user object.
EWS.User.HomePhone String Home phone of the user object.
EWS.User.Id String ID of the user object.
EWS.User.Identity String Identity of the user object.
EWS.User.Initials String Initials of the user object.
EWS.User.IsCloudCache Boolean Whether there is a cloud cache for the user object.
EWS.User.IsCloudCacheBlocked Boolean Whether the cloud cache is blocked.
EWS.User.IsCloudCacheProvisioningComplete Boolean Whether cloud cache provisioning is complete.
EWS.User.IsDirSynced Boolean Whether the directory is synched.
EWS.User.IsInactiveMailbox Boolean Whether the mailbox is inactive.
EWS.User.IsLinked Boolean Whether the user object is linked.
EWS.User.IsSecurityPrincipal Boolean Whether there is a security principal.
EWS.User.IsSoftDeletedByDisable Boolean Whether soft delete is disabled and hard (permanent) delete occurs.
EWS.User.IsSoftDeletedByRemove Boolean When the Exchange Online mailbox is deleted (soft delete), this property is set to True.
EWS.User.IsValid Boolean Whether the user object is valid.
EWS.User.LastName String Last name of the user object.
EWS.User.LegacyExchangeDN String Legacy exchange distinguished name of the user object.
EWS.User.LegalAgeGroup Unknown Legal age group of the user object.
EWS.User.LinkedMasterAccount String Linked master account of the user object.
EWS.User.MailboxLocations String Mailbox locations of the user object.
EWS.User.MailboxProvisioningConstraint Unknown Mailbox provisioning constraint of the user object.
EWS.User.MailboxRegion Unknown Mailbox region of the user object.
EWS.User.MailboxRegionLastUpdateTime Unknown Last time the mailbox region of the user object was updated.
EWS.User.MailboxRegionSuffix String Mailbox region suffix of the user object.
EWS.User.MailboxRelease String Mailbox release of the user object.
EWS.User.MailboxWorkloads String Mailbox workloads of the user object.
EWS.User.Manager Unknown Manager of the user object.
EWS.User.MicrosoftOnlineServicesID String Microsoft Online Services ID of the user object.
EWS.User.MobilePhone String Mobile phone of the user object.
EWS.User.Name String Name of the user object.
EWS.User.NetID String Network ID of the user object.
EWS.User.Notes String Notes for the user object.
EWS.User.ObjectCategory String Object category of the user object.
EWS.User.ObjectClass String Object class of the user object.
EWS.User.ObjectState String Object state of the user object.
EWS.User.Office String Office of the user object.
EWS.User.OrganizationId String Organization ID of the user object.
EWS.User.OrganizationalUnit String Organizational unit of the user object.
EWS.User.OriginatingServer String Originating server of the user object.
EWS.User.PSComputerName String PowerShell computer name of the user object.
EWS.User.PSShowComputerName Boolean Whether to show the PowerShell computer name of the user object.
EWS.User.Pager String Pager of the user object.
EWS.User.Phone String Phone of the user object.
EWS.User.PhoneticDisplayName String Phonetic display name of the user object.
EWS.User.PostalCode String Postal Code of the user object.
EWS.User.PreviousRecipientTypeDetails String Details of the previous recipient type of the user object.
EWS.User.RecipientType String Recipient type of the user object.
EWS.User.RecipientTypeDetails String Details of the recipient type of the user object.
EWS.User.RemotePowerShellEnabled Boolean Whether remote PowerShell is enabled for the user object.
EWS.User.ResetPasswordOnNextLogon Boolean Whether to reset the password on next logon.
EWS.User.RunspaceId String Runspace ID of the user object.
EWS.User.SKUAssigned Boolean Whether SKU is assigned.
EWS.User.SamAccountName String sAMAccountName of the user object.
EWS.User.SeniorityIndex Unknown Seniority index of the user object.
EWS.User.Sid String SID of the user object.
EWS.User.SimpleDisplayName String Simple display name of the user object.
EWS.User.StateOrProvince String State or province of the user object.
EWS.User.StreetAddress String Street address of the user object.
EWS.User.StsRefreshTokensValidFrom Date The validation start date for the Security Token Service (STS) refresh tokens of the user object.
EWS.User.TelephoneAssistant String Telephone assistant of the user object.
EWS.User.Title String Title of the user object.
EWS.User.UMDialPlan Unknown Unified Messaging (UM) dial plan of the user object.
EWS.User.UMDtmfMap String Unified Messaging (UM) dual tone multi-frequency (DTMF) map of the user object.
EWS.User.UpgradeDetails Unknown Upgrade details of the user object.
EWS.User.UpgradeMessage Unknown Upgrade message of the user object.
EWS.User.UpgradeRequest String Upgrade request of the user object.
EWS.User.UpgradeStage Unknown Upgrade stage of the user object.
EWS.User.UpgradeStageTimeStamp Unknown Upgrade stage time stamp of the user object.
EWS.User.UpgradeStatus String Upgrade status of the user object.
EWS.User.UserAccountControl String User account control of the user object.
EWS.User.UserPrincipalName String User principal name of the user object.
EWS.User.WebPage String Web page of the user object.
EWS.User.WhenChanged Date The date the user object was changed.
EWS.User.WhenChangedUTC Date The date in UTC format of when the user object was changed.
EWS.User.WhenCreated Date The date the user object was created.
EWS.User.WhenCreatedUTC Date The date in UTC format of when the user object was created.
EWS.User.WhenSoftDeleted Unknown When the user object was soft deleted.
EWS.User.WindowsEmailAddress String Windows email address of the user object.
EWS.User.WindowsLiveID String Windows live ID of the user object.
EWS.User.DirectReports String Direct reports of the user object.

ews-mailbox-audit-bypass-association-list


Retrieves information about the AuditBypassEnabled property value for user accounts (on-premises Exchange and the cloud) and computer accounts (on-premises Exchange only).

Base Command

ews-mailbox-audit-bypass-association-list

Input

Argument Name Description Required
identity The mailbox you want to view. Optional
domain_controller The domain controller that’s used by this cmdlet to read data from or write data to Active Directory. You identify the domain controller by its fully qualified domain name (FQDN). This argument is available only in on-premises Exchange. Optional
limit Maximum number of users to get. A value of 0 means to get all users. Default is 10. Optional

Context Output

Path Type Description
EWS.MailboxAuditBypassAssociation.AuditBypassEnabled Boolean Whether the mailbox audit bypass association is enabled.
EWS.MailboxAuditBypassAssociation.DistinguishedName String Distinguished name of the mailbox audit bypass association.
EWS.MailboxAuditBypassAssociation.ExchangeObjectId String Exchange object ID of the mailbox audit bypass association.
EWS.MailboxAuditBypassAssociation.ExchangeVersion String The version of the exchanged server.
EWS.MailboxAuditBypassAssociation.Guid String The GUID of the mailbox audit bypass association.
EWS.MailboxAuditBypassAssociation.Id String ID of the mailbox audit bypass association.
EWS.MailboxAuditBypassAssociation.Identity String The unique identity of the mailbox audit bypass association.
EWS.MailboxAuditBypassAssociation.IsValid Boolean Whether the mailbox audit bypass association property is enabled.
EWS.MailboxAuditBypassAssociation.Name String Name of the mailbox audit bypass association.
EWS.MailboxAuditBypassAssociation.ObjectCategory String Object category of the mailbox audit bypass association.
EWS.MailboxAuditBypassAssociation.ObjectClass String Object class of the mailbox audit bypass association.
EWS.MailboxAuditBypassAssociation.ObjectId String Object ID of the mailbox audit bypass association.
EWS.MailboxAuditBypassAssociation.ObjectState String Object state of the mailbox audit bypass association.
EWS.MailboxAuditBypassAssociation.OrganizationId String Organization ID of the mailbox audit bypass association.
EWS.MailboxAuditBypassAssociation.OriginatingServer String Originating server of the mailbox audit bypass association.
EWS.MailboxAuditBypassAssociation.PSComputerName String PowerShell computer name of the mailbox audit bypass association.
EWS.MailboxAuditBypassAssociation.PSShowComputerName Boolean Whether to show the computer name of the mailbox audit bypass association.
EWS.MailboxAuditBypassAssociation.RunspaceId String Runspace ID of the mailbox audit bypass association.
EWS.MailboxAuditBypassAssociation.WhenChanged unknown The date the mailbox audit bypass association was changed.
EWS.MailboxAuditBypassAssociation.WhenChangedUTC Date The date in UTC of when the mailbox audit bypass association was changed.
EWS.MailboxAuditBypassAssociation.WhenCreated Date The date the mailbox audit bypass association was created.
EWS.MailboxAuditBypassAssociation.WhenCreatedUTC Date The date in UTC format of when the mailbox audit bypass association was created.

ews-rule-list


Get a list of all mailbox rules.

Base Command

ews-rule-list

Input

Argument Name Description Required
mailbox The mailbox that contains the Inbox rule. Required
limit Maximum number of rules to get. A value of 0 means to get all rules Optional

Context Output

Path Type Description
EWS.Rule.RuleIdentity String The rule identity.
EWS.Rule.Name String The rule name.
EWS.Rule.Enabled Boolean Whether the rule is enabled or not.
EWS.Rule.Priority String the rule priority.

Human Readable Output

Results of ews-rule-list

Enabled Name Priority RuleIdentity
true CheckActionRequired 1 1268829516541722625
true ews phishing test 8 1845290268845146113

ews-get-rule


Get a mailbox rule.

Base Command

ews-get-rule

Input

Argument Name Description Required
mailbox The mailbox that contains the Inbox rule. Required
identity The ID of the rule. Required

Context Output

Path Type Description
EWS.Rule.Rule String The rule identity.
EWS.Rule.RuleName String The rule name.
EWS.Rule.IsEnabled Boolean Whether the rule is enabled or not.
EWS.Rule.Priority String The rule priority.
EWS.Rule.Description String The description of the rule.
EWS.Rule.StopProcessingRules Boolean Whether to stop processing the rule or not.
EWS.Rule.IsValid Boolean Whether the rule is valid or not.

Human Readable Output

Results of ews-rule-list

Enabled Name Priority RuleIdentity Description IsValid StopProcessingRules
true CheckActionRequired 1 1268829516541722625 If the message: the sender requested any action and my name is in the To box true false

ews-remove-rule


Remove a mailbox rule.

Base Command

ews-remove-rule

Input

Argument Name Description Required
mailbox The mailbox that contains the Inbox rule. Required
identity The ID of the rule. Required

Context Output

There are no context outputs for this command.

Human Readable Output

Rule 1845290268845146113 has been deleted successfully

ews-rule-disable


Disable an existing inbox rule in a given mailbox.

Base Command

ews-rule-disable

Input

Argument Name Description Required
mailbox The mailbox that contains the inbox rule. Required
identity The inbox rule that you want to disable. Required

Context Output

There are no context outputs for this command.

Human Readable Output

Rule 1845290268845146113 has been disabled successfully

ews-rule-enable


Enable an existing inbox rule in a given mailbox.

Base Command

ews-rule-enable

Input

Argument Name Description Required
mailbox The mailbox that contains the inbox rule. Required
identity The inbox rule that you want to enable. Required

Context Output

There are no context outputs for this command.

Human Readable Output

Rule 1845290268845146113 has been enabled successfully

ews-mail-flow-rules-list


List all mail flow rules (transport rules) in the organization.

Base Command

ews-mail-flow-rules-list

Input

Argument Name Description Required
extended_output Determine whether the output will be in verbose format or not. Optional
limit The amount of mail flow rules to return. Optional

Context Output

Path Type Description
EWS.MailFlowRule.Size Number The size of the mail flow rule in bytes, typically related to the storage or data usage of the rule.
EWS.MailFlowRule.ExpiryDate Date The date and time when the mail flow rule is set to expire and no longer apply.
EWS.MailFlowRule.Mode String The operational mode of the rule, indicating whether it is active (Enforce), in testing mode (Test), or disabled.
EWS.MailFlowRule.Quarantine Boolean Specifies whether the rule actions include quarantining messages that match the rule.
EWS.MailFlowRule.Guid String The unique identifier (Globally Unique Identifier) for the mail flow rule.
EWS.MailFlowRule.OrganizationId String The identifier for the organization where the mail flow rule is configured, typically used in multi-tenant environments.
EWS.MailFlowRule.DistinguishedName String The distinguished name of the mail flow rule in the Exchange directory structure.
EWS.MailFlowRule.IsValid Boolean Indicates whether the mail flow rule is valid and functional.
EWS.MailFlowRule.Conditions Array The conditions that trigger the mail flow rule, such as specific senders, recipients, or message properties.
EWS.MailFlowRule.Comments Unknown Free-form text field for adding comments or notes about the rule, typically used for documentation.
EWS.MailFlowRule.WhenChanged Date The date and time when the mail flow rule was last modified.
EWS.MailFlowRule.Description String A brief description of the mail flow rule’s purpose or functionality.
EWS.MailFlowRule.Actions Array The actions taken when a message matches the rule’s conditions, such as redirecting, blocking, or adding headers.
EWS.MailFlowRule.ImmutableId String A persistent, unchangeable identifier for the mail flow rule, ensuring it remains identifiable across modifications.
EWS.MailFlowRule.Identity String The identity of the rule, often combining the name and unique identifiers, used to reference the rule programmatically.
EWS.MailFlowRule.Name String The user-friendly name of the mail flow rule, typically used for easy identification.
EWS.MailFlowRule.CreatedBy String The user or process that created the mail flow rule.
EWS.MailFlowRule.RouteMessageOutboundConnector Unknown Specifies whether messages matching the rule should be routed through a specific outbound connector.

Human Readable Output

Results of ews-rule-list

Name State Priority Comment WhenChanged CreatedBy
demisto Disabled 1 comment 2019-10-14T07:25:04+00:00 Ed Testmaner
demisto-2 Enabled 2 comment 2019-11-15T010:21:45+00:00 Kemp Kimmons
demisto-3 Enabled 3 comment 2019-11-16T016:26:46+00:00 Barbara Wagner

ews-mail-flow-rule-get


Get a mail flow rule (transport rules) in the organization.

Base Command

ews-mail-flow-rule-get

Input

Argument Name Description Required
extended_output Determine whether the output will be in verbose format or not. Optional
identity Specifies the rule that you want to view. Optional

Context Output

Path Type Description
EWS.MailFlowRule.Size Number The size of the mail flow rule in bytes, typically related to the storage or data usage of the rule.
EWS.MailFlowRule.ExpiryDate Date The date and time when the mail flow rule is set to expire and no longer apply.
EWS.MailFlowRule.Mode String The operational mode of the rule, indicating whether it is active (Enforce), in testing mode (Test), or disabled.
EWS.MailFlowRule.Quarantine Boolean Specifies whether the rule actions include quarantining messages that match the rule.
EWS.MailFlowRule.Guid String The unique identifier (Globally Unique Identifier) for the mail flow rule.
EWS.MailFlowRule.OrganizationId String The identifier for the organization where the mail flow rule is configured, typically used in multi-tenant environments.
EWS.MailFlowRule.DistinguishedName String The distinguished name of the mail flow rule in the Exchange directory structure.
EWS.MailFlowRule.IsValid Boolean Indicates whether the mail flow rule is valid and functional.
EWS.MailFlowRule.Conditions Array The conditions that trigger the mail flow rule, such as specific senders, recipients, or message properties.
EWS.MailFlowRule.Comments Unknown Free-form text field for adding comments or notes about the rule, typically used for documentation.
EWS.MailFlowRule.WhenChanged Date The date and time when the mail flow rule was last modified.
EWS.MailFlowRule.Description String A brief description of the mail flow rule’s purpose or functionality.
EWS.MailFlowRule.Actions Array The actions taken when a message matches the rule’s conditions, such as redirecting, blocking, or adding headers.
EWS.MailFlowRule.ImmutableId String A persistent, unchangeable identifier for the mail flow rule, ensuring it remains identifiable across modifications.
EWS.MailFlowRule.Identity String The identity of the rule, often combining the name and unique identifiers, used to reference the rule programmatically.
EWS.MailFlowRule.Name String The user-friendly name of the mail flow rule, typically used for easy identification.
EWS.MailFlowRule.CreatedBy String The user or process that created the mail flow rule.
EWS.MailFlowRule.RouteMessageOutboundConnector Unknown Specifies whether messages matching the rule should be routed through a specific outbound connector.

Human Readable Output

Results of ews-rule-list

Name State Priority Comment WhenChanged CreatedBy
demisto Disabled 1 comment 2019-10-14T07:25:04+00:00 Ed Testmaner

ews-mail-flow-rule-remove


Remove a mail flow rule (transport rule) from the organization.

Base Command

ews-mail-flow-rule-remove

Input

Argument Name Description Required
identity The rule that you want to remove. Required

Context Output

There are no context outputs for this command.

Human Readable Output

Mail flow rule 1845290268845146113 has been removed successfully

ews-mail-flow-rule-disable


Disable a mail flow rule (transport rule) in the organization.

Base Command

ews-mail-flow-rule-disable

Input

Argument Name Description Required
identity The rule that you want to disable. Required

Context Output

There are no context outputs for this command.

Human Readable Output

Mail flow rule 1845290268845146113 has been disabled successfully

ews-mail-flow-rule-enable


Enable a mail flow rule (transport rule) in the organization.

Base Command

ews-mail-flow-rule-enable

Input

Argument Name Description Required
identity The rule that you want to enable. Required

Context Output

There are no context outputs for this command.

Human Readable Output

Mail flow rule 1845290268845146113 has been enabled successfully

ews-mail-flow-rule-create


Create a transport rule (mail flow rule) in the organization. A name must always be provided, either through the name argument or as a Name key inside the entry_id file. When no entry_id file is provided, both the name argument and at least one action (reject_message_reason_text, quarantine, or delete_message) are required.

Base Command

ews-mail-flow-rule-create

Input

Argument Name Description Required
name The unique name of the rule. The maximum length is 64 characters. If the value contains spaces, enclose the value in quotation marks (“). A name must always be provided, either through this argument or as a Name key inside the entry_id file. If both are provided, the value from the entry_id file takes precedence. Optional
mode How the rule operates. Possible values are: Audit, AuditAndNotify, Enforce. Optional
priority The priority value for the rule that determines the order of rule processing. A lower integer value indicates a higher priority, the value 0 is the highest priority, and rules can’t have the same priority value. Optional
from A comma-separated list of senders to look for in messages. You can use any value that uniquely identifies the sender, such as a name, alias, distinguished name, canonical DN, email address, or GUID. If a value contains spaces, enclose it in quotation marks (“). For example, to search for a sender with the name Chris and the alias Tech Writer, use the following syntax: Chris,”Tech Writer”. Optional
sent_to A comma-separated list of recipients to look for in messages. You can use any value that uniquely identifies the recipient, such as a name, alias, distinguished name, canonical DN, email address, or GUID. If a value contains spaces, enclose it in quotation marks (“). For example, to search for a recipient with the name Chris and the alias Tech Writer, use the following syntax: Chris,”Tech Writer”. Optional
subject_contains_words A comma-separated list of words or phrases to look for in the Subject field of messages. If a value contains spaces, as with a phrase, enclose it in quotation marks (“). For example: Word1,”Phrase with spaces”,word2. Optional
except_if_subject_contains_words A comma-separated list of words or phrases that, when found in the Subject field of messages, exempt the message from the rule. If a value contains spaces, as with a phrase, enclose it in quotation marks (“). For example: Word1,”Phrase with spaces”,word2. Optional
reject_message_reason_text The explanation text that’s used when the rule rejects messages. If the value contains spaces, enclose the value in quotation marks (“). When no entry_id file is provided, at least one of the actions (reject_message_reason_text, quarantine, or delete_message) must be provided. Optional
quarantine Whether to quarantine messages that match the rule. When no entry_id file is provided, at least one of the actions (reject_message_reason_text, quarantine, or delete_message) must be provided. Possible values are: true, false. Optional
delete_message Whether to silently drop messages without an NDR. When no entry_id file is provided, at least one of the actions (reject_message_reason_text, quarantine, or delete_message) must be provided. Possible values are: true, false. Optional
comments The descriptive text for the rule (for example, what the rule is used for, or how it has changed over time). Optional
entry_id The War Room entry ID of a JSON file that contains additional rule parameters as a map of parameter name to value (for example, {“Name”: “My rule”, “ActivationDate”: “09/01/2018”}). Use this to set parameters that are not exposed as dedicated command arguments. Values in the file take precedence over the corresponding command arguments. If the name argument is not provided, the file must include a Name key. Optional
extended_output Whether the output will be in verbose format. Possible values are: true, false. Optional

Context Output

Path Type Description
EWS.MailFlowRule.Size Number The size of the mail flow rule in bytes, typically related to the storage or data usage of the rule.
EWS.MailFlowRule.ExpiryDate Date The date and time when the mail flow rule is set to expire and no longer apply (e.g., 2024-01-15T12:34:56Z).
EWS.MailFlowRule.Mode String The operational mode of the rule, indicating whether it is active (Enforce), in testing mode (Test), or disabled.
EWS.MailFlowRule.Quarantine Boolean Specifies whether the rule actions include quarantining messages that match the rule.
EWS.MailFlowRule.Guid String The Globally Unique Identifier for the mail flow rule.
EWS.MailFlowRule.OrganizationId String The identifier for the organization where the mail flow rule is configured, typically used in multi-tenant environments.
EWS.MailFlowRule.DistinguishedName String The distinguished name of the mail flow rule in the Exchange directory structure.
EWS.MailFlowRule.IsValid Boolean Indicates whether the mail flow rule is valid and functional.
EWS.MailFlowRule.Conditions Unknown The conditions that trigger the mail flow rule, such as specific senders, recipients, or message properties.
EWS.MailFlowRule.Comments Unknown Free-form text field for adding comments or notes about the rule, typically used for documentation.
EWS.MailFlowRule.WhenChanged Date The date and time when the mail flow rule was last modified (e.g., 2024-01-15T12:34:56Z).
EWS.MailFlowRule.Description String A brief description of the mail flow rule’s purpose or functionality.
EWS.MailFlowRule.Actions Unknown The actions taken when a message matches the rule’s conditions, such as redirecting, blocking, or adding headers.
EWS.MailFlowRule.ImmutableId Unknown A persistent, unchangeable identifier for the mail flow rule, ensuring it remains identifiable across modifications.
EWS.MailFlowRule.Identity String The identity of the rule, often combining the name and unique identifiers, used to reference the rule programmatically.
EWS.MailFlowRule.Name String The user-friendly name of the mail flow rule, typically used for easy identification.
EWS.MailFlowRule.CreatedBy String The user or process that created the mail flow rule.
EWS.MailFlowRule.RouteMessageOutboundConnector Unknown Specifies whether messages matching the rule should be routed through a specific outbound connector.

Command example

!ews-mail-flow-rule-create name="My Rule" mode=Enforce priority=0 subject_contains_words="confidential" quarantine=true comments="Created by playbook"

Human Readable Output

Mail flow rule ‘My Rule’ was created successfully

Name State Mode Priority IsRuleConfigurationSupported Comments
My Rule Enabled Enforce 0 true Created by playbook

ews-mail-flow-rule-update


Modify an existing transport rule (mail flow rule) in the organization. An identity must always be provided, either through the identity argument or as an Identity key inside the entry_id file. When no entry_id file is provided, the identity argument is required.

Base Command

ews-mail-flow-rule-update

Input

Argument Name Description Required
identity The rule that you want to modify. You can use any value that uniquely identifies the rule, such as a name, distinguished name, or GUID. An identity must always be provided, either through this argument or as an Identity key inside the entry_id file. If both are provided, the value from the entry_id file takes precedence. Optional
mode How the rule operates. Possible values are: Audit, AuditAndNotify, Enforce. Optional
priority The priority value for the rule that determines the order of rule processing. A lower integer value indicates a higher priority, the value 0 is the highest priority, and rules can’t have the same priority value. Optional
from A comma-separated list of senders to look for in messages. You can use any value that uniquely identifies the sender, such as a name, alias, distinguished name, canonical DN, email address, or GUID. If a value contains spaces, enclose it in quotation marks (“). For example, to search for a sender with the name Chris and the alias Tech Writer, use the following syntax: Chris,”Tech Writer”. Optional
sent_to A comma-separated list of recipients to look for in messages. You can use any value that uniquely identifies the recipient, such as a name, alias, distinguished name, canonical DN, email address, or GUID. If a value contains spaces, enclose it in quotation marks (“). For example, to search for a recipient with the name Chris and the alias Tech Writer, use the following syntax: Chris,”Tech Writer”. Optional
subject_contains_words A comma-separated list of words or phrases to look for in the Subject field of messages. If a value contains spaces, as with a phrase, enclose it in quotation marks (“). For example: Word1,”Phrase with spaces”,word2. Optional
except_if_subject_contains_words A comma-separated list of words or phrases that, when found in the Subject field of messages, exempt the message from the rule. If a value contains spaces, as with a phrase, enclose it in quotation marks (“). For example: Word1,”Phrase with spaces”,word2. Optional
reject_message_reason_text The explanation text that’s used when the rule rejects messages. If the value contains spaces, enclose the value in quotation marks (“). Optional
quarantine Whether to quarantine messages that match the rule. Possible values are: true, false. Optional
delete_message Whether to silently drop messages without an NDR. Possible values are: true, false. Optional
comments The descriptive text for the rule (for example, what the rule is used for, or how it has changed over time). Optional
entry_id The War Room entry ID of a JSON file that contains additional rule parameters as a map of parameter name to value (for example, {“Identity”: “My rule”, “ActivationDate”: “09/01/2018”}). Use this to set parameters that are not exposed as dedicated command arguments. Values in the file take precedence over the corresponding command arguments. If the identity argument is not provided, the file must include an Identity key. Optional

Context Output

There are no context outputs for this command.

Command example

!ews-mail-flow-rule-update identity="My Rule" priority=1 comments="Updated by playbook"

Human Readable Output

Mail flow rule 1845290268845146113 has been updated successfully

ews-mail-forwarding-disable


Disable mail forwarding for a given user.

Base Command

ews-mail-forwarding-disable

Input

Argument Name Description Required
identity The mailbox that you want to modify. Required

Context Output

There are no context outputs for this command.

Human Readable Output

Mail forwarding for user 1845290268845146113 has been disabled successfully

```

Configuration parameters

  • url — Exchange Online URL (required)
  • certificate — (required)
  • password — (required)
  • organization — The organization used in app-only authentication. (required)
  • app_id — The application ID from the Azure portal (required)

Commands (37)

  • ews-cas-mailbox-list

    Displays Client Access settings that are configured on mailboxes.

  • ews-email-security-block-sender-office-365-quick-action

    Add new items to the Tenant Allow/Block Lists. Uses PowerShell New-TenantAllowBlockListItems cmdlet.

  • ews-email-security-unblock-sender-office-365-quick-action

    Remove items from the Tenant's Allow/Block Lists. You can delete items by their value or by their unique ID. Uses the PowerShell cmdlet Remove-TenantAllowBlockListItems cmdlet.

  • ews-export-quarantinemessage

    Export quarantine messages. Uses PowerShell Export-QuarantineMessage cmdlet.

  • ews-federation-configuration-get

    Retrieves the Exchange organization's federated organization identifier and related details, such as federated domains, organization contact, and status.

  • ews-federation-trust-get

    Displays the federation trust configured for the Exchange organization.

  • ews-get-quarantinemessage

    Retrieve quarantine messages. Uses PowerShell Get-QuarantineMessage cmdlet.

  • ews-get-rule

    Retrieve information about the Inbox rule properties.

  • ews-get-tenant-allow-block-list-count

    Retrieve current count of defined Tenant Allow/Block List items. Uses Get-TenantAllowBlockListItems cmdlet.

  • ews-get-tenant-allow-block-list-items

    Retrieve current Tenant Allow/Block List items. Uses Get-TenantAllowBlockListItems cmdlet.

  • ews-global-junk-rules-set

    Sets junk rules in all managed accounts.

  • ews-junk-rules-get

    Gets junk rules for the specified mailbox.

  • ews-junk-rules-set

    Sets junk rules for the specified mailbox.

  • ews-mail-flow-rule-create

    Create a transport rule (mail flow rule) in the organization. A name must always be provided, either through the `name` argument or as a `Name` key inside the entry_id file. When no entry_id file is provided, both the `name` argument and at least one action (`reject_message_reason_text`, `quarantine`, or `delete_message`) are required.

  • ews-mail-flow-rule-disable

    Disable a mail flow rule (transport rule) in the organization.

  • ews-mail-flow-rule-enable

    Enable a mail flow rule (transport rule) in the organization.

  • ews-mail-flow-rule-get

    Get a mail flow rule (transport rules) in the organization.

  • ews-mail-flow-rule-remove

    Remove a mail flow rule (transport rule) from the organization.

  • ews-mail-flow-rule-update

    Modify an existing transport rule (mail flow rule) in the organization. An identity must always be provided, either through the `identity` argument or as an `Identity` key inside the entry_id file. When no entry_id file is provided, the `identity` argument is required.

  • ews-mail-flow-rules-list

    List all mail flow rules (transport rules) in the organization.

  • ews-mail-forwarding-disable

    Disable mail forwarding for a given user.

  • ews-mailbox-audit-bypass-association-list

    Retrieves information about the AuditBypassEnabled property value for user accounts (on-premises Exchange and the cloud) and computer accounts (on-premises Exchange only).

  • ews-mailbox-list

    Displays mailbox objects and attributes, populate property pages, or supplies mailbox information to other tasks.

  • ews-mailbox-permission-list

    Retrieves permissions on a mailbox.

  • ews-message-trace-get Deprecated

    (Deprecated) Searches message data for the last 10 days. If you run this command without any arguments, only data from the last 48 hours is returned. If you enter a start date that is older than 10 days, you will receive an error and the command will return no results. This command returns a maximum of 1,000,000 results, and will timeout on very large queries. If your query returns too many results, consider splitting it up using shorter start_date and end_date intervals.

  • ews-message-trace-list

    Searches message data from the last 90 days. If you run this command without any arguments, only data from the last 48 hours is returned. If you enter a start date that is older than 90 days, you will receive an error and the command will return no results. This command returns a maximum of 1,000,000 results, and will timeout on very large queries. If your query returns too many results, consider splitting it up using shorter start_date and end_date intervals.

  • ews-new-tenant-allow-block-list-items

    Add new items to the Tenant Allow/Block Lists. Uses PowerShell New-TenantAllowBlockListItems cmdlet.

  • ews-recipient-list

    Displays existing recipient objects in your organization. This command returns all mail-enabled objects (for example, mailboxes, mail users, mail contacts, and distribution groups).

  • ews-recipient-permission-list

    Displays information about SendAs permissions that are configured for users.

  • ews-release-quarantinemessage

    Releases the quarantined messages. Uses the PowerShell Release-QuarantineMessage cmdlet.

  • ews-remote-domain-get

    Gets the configuration information for the remote domains configured in your organization. This command is available only in the Exchange Online PowerShell V2 module.

  • ews-remove-rule

    Remove an Inbox rule.

  • ews-remove-tenant-allow-block-list-items

    Remove items from the tenant's Allow/Block Lists. You can delete items by their value or by their unique ID. Uses the PowerShell cmdlet Remove-TenantAllowBlockListItems cmdlet.

  • ews-rule-disable

    Disable an existing inbox rule in a given mailbox.

  • ews-rule-enable

    Enable an existing inbox rule in a given mailbox.

  • ews-rule-list

    Retrieve a list of an Inbox rules.

  • ews-user-list

    Displays the existing user objects in your organization.

. $PSScriptRoot\CommonServerPowerShell.ps1
<# IMPORTANT NOTICE
# When conencting to ExchangeOnline - only needed command between CreateSession
# and DisconnectSession and let also the `finally` term to disconnect (it will do nothing if everything is fine).
# This will reduce the time sessions are opened between Exchange and the server and will create
# less problems.
# DO NOT USE ONE FINALLY STATEMENT: we don't know if and when it'll be executed and anyway it the DisconnectSession
# should be called before returning results to the server.
#>
Import-Module ExchangeOnlineManagement

# Disable PowerShell progress bars, as they aren't helpful in a non-interactive script
$Global:ProgressPreference = 'SilentlyContinue'

$script:INTEGRATION_NAME = "EWS extension"
$script:COMMAND_PREFIX = "ews"
$script:INTEGRATION_ENTRY_CONTEXT = "EWS"
$script:JUNK_RULE_ENTRY_CONTEXT = "$script:INTEGRATION_ENTRY_CONTEXT.Rule.Junk(val.Email && val.Email == obj.Email)"
$script:MESSAGE_TRACE_ENTRY_CONTEXT = "$script:INTEGRATION_ENTRY_CONTEXT.MessageTrace(val.messageTraceId.value && val.messageTraceId.value == obj.messageTraceId.value)"


function ParseJunkRulesToEntryContext([PSObject]$raw_response) {
    return @{
        $script:JUNK_RULE_ENTRY_CONTEXT = @{
            "MailboxOwnerId"              = $raw_response.MailboxOwnerId
            "Identity"                    = $raw_response.Identity
            "BlockedSendersAndDomains"    = $raw_response.BlockedSendersAndDomains
            "TrustedRecipientsAndDomains" = $raw_response.TrustedRecipientsAndDomains
            "TrustedSendersAndDomains"    = $raw_response.TrustedSendersAndDomains
            "TrustedListsOnly"            = $raw_response.TrustedListsOnly
            "ContactsTrusted"             = $raw_response.ContactsTrusted
            "Enabled"                     = $raw_response.Enabled
        }
    }

    <#
        .DESCRIPTION
        Parse junk rules raw response.

        .PARAMETER raw_response
        Junk rules raw response.

        .EXAMPLE
        ParseJunkRulesToEntryContext $raw_response

        .OUTPUTS
        PSObject - entry context.
    #>
}


function ParseMessageTraceToEntryContext([PSObject]$raw_response) {
    $entry_context = @{}
    if ($raw_response) {
        $entry_context = @{
            $script:MESSAGE_TRACE_ENTRY_CONTEXT = $raw_response | ForEach-Object {
                $entry = @{
                    "MessageId"        = $_.MessageId
                    "MessageTraceId"   = $_.MessageTraceId
                    "Received"         = $_.Received
                    "RecipientAddress" = $_.RecipientAddress
                    "SenderAddress"    = $_.SenderAddress
                    "Size"             = $_.Size
                    "Status"           = $_.Status
                    "Subject"          = $_.Subject
                    "ToIP"             = $_.ToIP
                    "FromIP"           = $_.FromIP
                }

                if ($_.EndDate -ne $null) {
                    $entry["EndDate"] = $_.EndDate
                }
                if ($_.StartDate -ne $null) {
                    $entry["StartDate"] = $_.StartDate
                }
                if ($_.Organization -ne $null) {
                    $entry["Organization"] = $_.Organization
                }
                if ($_.Index -ne $null) {
                    $entry["Index"] = $_.Index
                }
                return $entry
            }
        }
    }

    return $entry_context
    <#
        .DESCRIPTION
        Parse message trace raw response.

        .PARAMETER raw_response
        Message trace raw response.

        .EXAMPLE
        ParseMessageTraceToEntryContext $raw_response

        .OUTPUTS
        PSObject - entry context.
    #>
}

function ParseRawResponse([PSObject]$response) {
    $items = @()
    ForEach ($item in $response){
        if ($item -Is [HashTable])
            {
        # Need to convert hashtables to ordered dicts so that the keys/values will be in the same order
            $item = $item | ConvertTo-OrderedDict
            }
        elseif ($item -Is [PsCustomObject]){
            $newItem = @{}
            $item.PSObject.Properties | ForEach-Object { $newItem[$_.Name] = $_.Value }
            $item = $newItem | ConvertTo-OrderedDict
        }

        if($item.Keys -contains "RuleIdentity"){
            $item.RuleIdentity = ($item.RuleIdentity).ToString()
        }
        $items += $item
    }
    return $items
}

function MailFlowRuleHelperFunction($raw_response, $extended_output) {
    $parsed_raw_response = ParseRawResponse $raw_response
    $entry_context = MailFlowRuleEntryContext $parsed_raw_response (ConvertTo-Boolean $extended_output)
    $md_columns = $raw_response | Select-Object -Property Name, State, Priority, Comment, WhenChanged, CreatedBy
    $human_readable = TableToMarkdown $md_columns "Results of $command"
    return $human_readable, $entry_context, $parsed_raw_response
    <#
        .DESCRIPTION
        A helper function to process the mail flow rule response.
        This function takes the raw response from a mail flow rule operation, parses it, and generates
        the necessary output for display and further processing.

        .PARAMETER raw_response
        The raw response obtained from the mail flow rule operation.

        .PARAMETER extended_output
        A flag indicating whether to include extended output in the response.

        .EXAMPLE
        $response = MailFlowRuleHelperFunction $raw_response $extended_output

        .OUTPUTS
        - $human_readable: The response formatted as a human-readable Markdown table.
        - $entry_context: The entry context hashtable.
        - $parsed_raw_response: The parsed raw response object.
    #>
}

function MailFlowRuleCreateEntryContext($parsed_raw_response) {
    $entry_context = @{}
    $entries = @()
    $parsed_raw_response | ForEach-Object {
        $entry = @{
            "Size"                          = $_.Size
            "ExpiryDate"                    = $_.ExpiryDate
            "Mode"                          = $_.Mode
            "Quarantine"                    = $_.Quarantine
            "Guid"                          = $_.Guid
            "OrganizationId"                = $_.OrganizationId
            "DistinguishedName"             = $_.DistinguishedName
            "IsValid"                       = $_.IsValid
            "Conditions"                    = $_.Conditions
            "Comments"                      = $_.Comments
            "WhenChanged"                   = $_.WhenChanged
            "Description"                   = $_.Description
            "Actions"                       = $_.Actions
            "ImmutableId"                   = $_.ImmutableId
            "Identity"                      = $_.Identity
            "Name"                          = $_.Name
            "CreatedBy"                     = $_.CreatedBy
            "RouteMessageOutboundConnector" = $_.RouteMessageOutboundConnector
        }
        $entries += $entry
    }
    $entry_context["$script:INTEGRATION_ENTRY_CONTEXT.MailFlowRules(obj.Guid === val.Guid)"] = $entries
    return $entry_context
    <#
        .DESCRIPTION
        Parse Maile flow rule raw response for limited output.

        .PARAMETER raw_response
        Mail Rule parsed raw response.

        .EXAMPLE
        MailFlowRuleCreateEntryContext $parsed_raw_response

        .OUTPUTS
        PSObject - entries context.
    #>
}

function MailFlowRuleEntryContext($parsed_raw_response, $extended_output) {
    # if "extended_output" is false (default) the output context is just the selected rule fields
    # if "extended_output" is true the output context is the full parsed response
    if ($extended_output) {
        return @{"$script:INTEGRATION_ENTRY_CONTEXT.MailFlowRules(obj.Guid === val.Guid)" = $parsed_raw_response}
    }
    return MailFlowRuleCreateEntryContext $parsed_raw_response
    <#
        .DESCRIPTION
        Selects the entry context for a mail flow rule response based on the extended_output flag.
        Centralizes the choice between the full parsed response and the limited selected-fields
        context so it stays consistent across commands.

        .PARAMETER parsed_raw_response
        The parsed raw response object.

        .PARAMETER extended_output
        Whether to return the full response context (true) or the limited context (false).

        .OUTPUTS
        Hashtable - The entry context.
    #>
}

class ExchangeOnlinePowershellV3Client
{
    [string]$url
    [System.Security.Cryptography.X509Certificates.X509Certificate2]$certificate
    [string]$organization
    [string]$app_id
    [SecureString]$password
    ExchangeOnlinePowershellV3Client(
            [string]$url,
            [string]$app_id,
            [string]$organization,
            [string]$certificate,
            [SecureString]$password
    )
    {
        $this.url = $url
        try
        {
            $ByteArray = [System.Convert]::FromBase64String($certificate)
        }
        catch
        {
            throw "Could not decode the certificate. Try to re-enter it"
        }
        $this.certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($ByteArray, $password)

        $this.organization = $organization
        $this.app_id = $app_id
    }
    CreateSession()
    {
        $cmd_params = @{
            "AppID" = $this.app_id
            "Organization" = $this.organization
            "Certificate" = $this.certificate
        }
        Connect-ExchangeOnline @cmd_params -ShowBanner:$false -CommandName New-TenantAllowBlockListItems,Get-TenantAllowBlockListItems,Remove-TenantAllowBlockListItems,Get-RemoteDomain,Get-MailboxAuditBypassAssociation,Get-User,Get-FederatedOrganizationIdentifier,Get-FederationTrust,Get-MessageTrace,Get-MessageTraceV2,Set-MailboxJunkEmailConfiguration,Get-Mailbox,Get-MailboxJunkEmailConfiguration,Get-InboxRule,Remove-InboxRule,Export-QuarantineMessage,Get-QuarantineMessage,Release-QuarantineMessage,Disable-InboxRule,Enable-InboxRule,Get-TransportRule,New-TransportRule,Set-TransportRule,Remove-TransportRule,Disable-TransportRule,Enable-TransportRule,Set-Mailbox -WarningAction:SilentlyContinue | Out-Null
    }
    DisconnectSession()
    {
        Disconnect-ExchangeOnline -Confirm:$false -WarningAction:SilentlyContinue 6>$null | Out-Null
        # Remove any lingering tmpEXO_ directories to prevent filling the disk
        Remove-Item -Path "/tmp/tmpEXO_*" -Recurse -Force
    }
    [PSObject]
    GetEXOCASMailbox(
            [string]$identity,
            [string]$organizational_unit,
            [string]$primary_smtp_address,
            [string]$user_principal_name,
            [int]$limit
    )
    {
        $cmd_params = @{ }
        if ($identity)
        {
            $cmd_params.Identity = $identity
        }
        if ($organizational_unit)
        {
            $cmd_params.OrganizationalUnit = $organizational_unit
        }
        if ($primary_smtp_address)
        {
            $cmd_params.PrimarySmtpAddress = $primary_smtp_address
        }
        if ($user_principal_name)
        {
            $cmd_params.UserPrincipalName = $user_principal_name
        }
        $this.CreateSession()
        if ($limit -gt 0)
        {
            $results = Get-EXOCASMailbox @cmd_params -ResultSize $limit
        }
        else
        {
            $results = Get-EXOCASMailbox @cmd_params -ResultSize Unlimited
        }
        $this.DisconnectSession()
        return $results

        <#
        .DESCRIPTION
        This cmdlet returns a variety of client access settings for one or more mailboxes.
        These settings include options for Outlook on the web, Exchange ActiveSync, POP3, and IMAP4.
        This cmdlet is available only in the Exchange Online PowerShell V2 module.

        .PARAMETER identity
        The Identity parameter specifies the mailbox you want to view.
        For the best performance, we recommend using the following values:
            * User ID or user principal name (UPN)
            * GUID

        Otherwise, you can use any value that uniquely identifies the mailbox. For example:
            * Name
            * Alias
            * Distinguished name (DN)
            * Domain\Username
            * Email address
            * LegacyExchangeDN
            * SamAccountName

        .PARAMETER organizational_unit
        The OrganizationalUnit parameter filters the results based on the object's location in Active Directory.

        .PARAMETER primary_smtp_address
        The PrimarySmtpAddress identifies the mailbox that you want to view by primary SMTP email address (for example, navin@contoso.onmicrosoft.com).
        Can't be used with user_principal_name.

        .PARAMETER user_principal_name
        The UserPrincipalName parameter identifies the mailbox that you want to view by UPN (for example, navin@contoso.onmicrosoft.com).
        Can't be used with primary_smtp_address.

        .EXAMPLE
        GetEXOCasMailbox("1254y894-feae-9yn7-a3e1-f2483a154tft")

        .OUTPUTS
        PSObject - Raw response

        .LINK
        https://docs.microsoft.com/en-us/powershell/module/exchange/get-exocasmailbox?view=exchange-ps
        #>
    }

    [PSObject]
    GetEXOMailbox(
            [string]$identity,
            [string]$property_sets,
            [int]$limit
    )
    {
        $cmd_params = @{ }
        if ($identity)
        {
            $cmd_params.Identity = $identity
        }
        if ($property_sets)
        {
            $cmd_params.PropertySets = $property_sets
        }
        $this.CreateSession()
        if ($limit -gt 0)
        {
            $results = Get-EXOMailbox @cmd_params -ResultSize $limit
        }
        else
        {
            $results = Get-EXOMailbox @cmd_params -ResultSize Unlimited
        }
        $this.DisconnectSession()
        return $results
        <#
        .DESCRIPTION
        Use the Get-EXOMailbox cmdlet to view mailbox objects and attributes,
        populate property pages, or supply mailbox information to other tasks.
        This cmdlet is available only in the Exchange Online PowerShell V2 module

        .PARAMETER identity
        The Identity parameter specifies the mailbox you want to view.
        For the best performance, we recommend using the following values:
            * User ID or user principal name (UPN)
            * GUID

        Otherwise, you can use any value that uniquely identifies the mailbox. For example:
            * Name
            * Alias
            * Distinguished name (DN)
            * Domain\Username
            * Email address
            * LegacyExchangeDN
            * SamAccountName

        .EXAMPLE
        GetEXOMailbox("1254y894-feae-9yn7-a3e1-f2483a154tft")

        .OUTPUTS
        PSObject - Raw response

        .LINK
        https://docs.microsoft.com/en-us/powershell/module/exchange/get-exomailbox?view=exchange-ps
        #>
    }

    [PSObject]
    GetEXOMailboxPermission(
            [string]$identity
    )
    {
        # Import and Execute command
        $cmd_params = @{ }
        if ($identity)
        {
            $cmd_params.Identity = $identity
        }
        $this.CreateSession()
        $results = Get-EXOMailboxPermission @cmd_params
        $this.DisconnectSession()
        return $results

        <#
        .DESCRIPTION
        View information about SendAs permissions that are configured for users.
        This command is available only in the Exchange Online PowerShell V2 module.

        .PARAMETER identity
        The Identity parameter the user that you want to view. You can use any value that uniquely identifies the user

        .EXAMPLE
        GetEXOMailboxPermission("1254y894-feae-9yn7-a3e1-f2483a154tft")

        .OUTPUTS
        PSObject - Raw response

        .LINK
        https://docs.microsoft.com/en-us/powershell/module/exchange/get-exomailboxpermission?view=exchange-ps
        #>
    }
    [PSObject]
    GetEXORecipientPermission(
            [string]$identity,
            [int]$limit
    )
    {
        $this.CreateSession()

        $cmd_params = @{ }
        if ($identity) {
            $cmd_params.Identity = $identity
        }
        if ($limit -gt 0) {
            $cmd_params.ResultSize = $limit
        } else  {
            $cmd_params.ResultSize = Unliimited
        }
        $results = Get-EXORecipientPermission @cmd_params

        $this.DisconnectSession()
        return $results
        <#
        .DESCRIPTION
        Use the Get-EXORecipientPermission cmdlet to view information about SendAs permissions that are
        configured for users in a cloud-based organization.
        This command is available only in the Exchange Online PowerShell V2 module

        .PARAMETER identity
        The Identity parameter specifies the mailbox you want to view.
        For the best performance, we recommend using the following values:
            * User ID or user principal name (UPN)
            * GUID

        Otherwise, you can use any value that uniquely identifies the mailbox. For example:
            * Name
            * Alias
            * Distinguished name (DN)
            * Domain\Username
            * Email address
            * LegacyExchangeDN
            * SamAccountName
        #>
    }
    [PSObject]
    GetEXORecipient(
            [string]$identity,
            [int]$limit
    )
    {
        $cmd_params = @{ Properties="Guid" }
        if ($identity)
        {
            $cmd_params.Identity = $identity
        }
        $this.CreateSession()
        if ($limit -gt 0)
        {
            $results = Get-EXORecipient @cmd_params -ResultSize $limit
        }
        else
        {
            $results = Get-EXORecipient @cmd_params -ResultSize Unlimited
        }
        $this.DisconnectSession()
        return $results
        <#
            .DESCRIPTION
            Use the Get-ExORecipient cmdlet to view existing recipient objects in your organization.
            This cmdlet returns all mail-enabled objects (for example,
            mailboxes, mail users, mail contacts, and distribution groups).

            #>
    }

    [PSObject]
    EXONewTenantAllowBlockList(
            [string]$entries,
            [string]$list_type,
            [string]$list_subtype,
            [string]$action,
            [string]$notes,
            [bool]$no_expiration,
            [string]$expiration_date
    )
    {
        $cmd_params = @{ }
        $entries_array = @()
        if ($entries.Contains(','))
        {
            $entries_array = $entries -split ','
        }
        if ($entries -and -not $entries_array)
        {
            $entries_array += $entries
            $cmd_params.Entries = $entries_array
        }
        else
        {
            $cmd_params.Entries = $entries_array
        }
        if ($list_type)
        {
            $cmd_params.ListType = $list_type
        }
        if ($list_subtype)
        {
            $cmd_params.ListSubType = $list_subtype
        }
        if ($notes)
        {
            $cmd_params.Notes = $notes
        }
        if ($no_expiration)
        {
            $cmd_params.NoExpiration = $null
        }
        if ($expiration_date)
        {
            $cmd_params.ExpirationDate = $expiration_date
        }
        if ($action -eq "Block")
        {
            $cmd_params.Block = $null
        }
        if ($action -eq "Allow")
        {
            $cmd_params.Allow = $null
        }
        $this.CreateSession()
        $results = New-TenantAllowBlockListItems @cmd_params
        $this.DisconnectSession()
        return $results
        <#
            .DESCRIPTION
            Use the New-TenantAllowBlockListItems cmdlet to add new entries to the Tenant Allow/Block Lists for your organization.
            This cmdlet returns all new entries created, details about them, and their status

            .LINK
            https://learn.microsoft.com/en-us/powershell/module/exchange/new-tenantallowblocklistitems?view=exchange-ps

        #>
    }

    [PSObject]
    EXOExportQuarantineMessage(
        [string[]]$identities,
        [string]$identity,
        [bool]$compress_output,
        [string]$entity_type,
        [bool]$force_conversion_to_mime,
        [string]$password,
        [string]$reason_for_export,
        [string]$recipient_address
    )
    {
        $zipErrMsg = "Using this argument requires 'compress_output' argument to be set to true."
        $results = ""
        try {
            $cmd_params = @{ }
            if ($identities)
            {
                $identities = $identities.Split(",").Trim()
                $cmd_params.Identities = $identities
            }
            if ($identity)
            {
                $cmd_params.Identity = $identity
            }
            if ($compress_output)
            {
                $cmd_params.CompressOutput = $true
            }
            if ($entity_type)
            {
                $cmd_params.EntityType = $entity_type
            }
            if ($force_conversion_to_mime)
            {
                $cmd_params.ForceConversionToMime = $true
            }
            if ($password)
            {
                if ($compress_output -eq $false) {
                    throw $zipErrMsg
                }
                $cmd_params.PasswordV2 = $password
            }
            if ($reason_for_export)
            {
                if ($compress_output -eq $false) {
                    throw $zipErrMsg
                }
                $cmd_params.ReasonForExport = $reason_for_export
            }
            if ($recipient_address)
            {
                $cmd_params.RecipientAddress = $recipient_address
            }
            $this.CreateSession()
            $results = Export-QuarantineMessage @cmd_params
        }
        finally {
            $this.DisconnectSession()
        }
        if ($null -eq $results) {
            return @{}
        } else {
            return $results
        }
        <#
            .DESCRIPTION
            Use the Export-QuarantineMessage cmdlet to export messages from quarantine in your organization.
            This cmdlet allows you to export one or more messages in various formats.

            .LINK
            https://learn.microsoft.com/en-us/powershell/module/exchange/export-quarantinemessage?view=exchange-ps
        #>
    }

    [PSObject]
    EXOGetQuarantineMessage(
        [hashtable]$params
    )
    {
        $results = ""
        try {
            $cmd_params = @{}
            $param_keys = @("Identity", "EntityType", "RecipientAddress", "SenderAddress", "TeamsConversationTypes",
                            "Direction", "Domain", "EndExpiresDate", "EndReceivedDate", "MessageId", "Page",
                            "PageSize", "PolicyName", "PolicyTypes", "QuarantineTypes", "RecipientTag",
                            "ReleaseStatus", "StartExpiresDate", "StartReceivedDate", "Subject", "Type")

            foreach ($key in $param_keys) {
                if ($params.$key) {
                    $cmd_params.$key = $params.$key
                }
            }

            if ($params.IncludeMessagesFromBlockedSenderAddress -eq $true) { $cmd_params.IncludeMessagesFromBlockedSenderAddress = $true }
            if ($params.MyItems -eq $true) { $cmd_params.MyItems = $true }
            if ($params.Reported -eq $true) { $cmd_params.Reported = $true }

            $this.CreateSession()
            $results = Get-QuarantineMessage @cmd_params
        }
        finally {
            $this.DisconnectSession()
        }
        if ($null -eq $results) {
            return @{}
        } else {
            return $results
        }
    }


    [PSObject]
    EXOReleaseQuarantineMessage(
        [string]$user,
        [string[]]$identities,
        [string]$identity,
        [bool]$release_to_all,
        [bool]$allow_sender,
        [string]$entity_type,
        [bool]$force,
        [bool]$report_false_positive,
        [string]$action_type
    )
    {
        if (-not $identities -and -not $identity) {
            return ""
        }
        try {
            $cmd_params = @{ }
            if ($user) {
                $cmd_params.User = $user
            }
            if ($release_to_all) {
                $cmd_params.ReleaseToAll = $release_to_all
            }
            if ($identities) {
                $identities = $identities.Split(",").Trim()
                $cmd_params.Identities = $identities
            }
            if ($identity) {
                $cmd_params.Identity = $identity
            }
            if ($allow_sender) {
                $cmd_params.AllowSender = $null
            }
            if ($entity_type) {
                $cmd_params.EntityType = $entity_type
            }
            if ($force) {
                $cmd_params.Force = $null
            }
            if ($report_false_positive) {
                $cmd_params.ReportFalsePositive = $null
            }
            if ($action_type) {
                $cmd_params.ActionType = $action_type
            }
            $this.CreateSession()
            Release-QuarantineMessage @cmd_params
        }
        finally {
            $this.DisconnectSession()
        }
        return ""
        <#
            .DESCRIPTION
            Use the Release-QuarantineMessage cmdlet to release messages from quarantine in your organization.
            This cmdlet allows you to release one or more messages and manage sender allow lists.

            .LINK
            https://learn.microsoft.com/en-us/powershell/module/exchange/release-quarantinemessage?view=exchange-ps
        #>
    }
    [PSObject]
    EXORemoveTenantAllowBlockList(
            [string]$entries,
            [string]$ids,
            [string]$list_type,
            [string]$list_subtype
    )
    {
        $cmd_params = @{ }
        $entries_array = @()
        $ids_array = @()
        if ($entries.Contains(','))
        {
            $entries_array = $entries -split ','
        }
        if ($entries -and -not $entries_array)
        {
            $entries_array += $entries
            $cmd_params.Entries = $entries_array
        }
        elseif ($entries_array)
        {
            $cmd_params.Entries = $entries_array
        }
        if ($ids -and $ids.Contains(','))
        {
            $ids_array = $ids -split ','
        }
        if ($ids_array)
        {
            $cmd_params.Ids = $ids_array
        }
        if ($list_type)
        {
            $cmd_params.ListType = $list_type
        }
        if ($list_subtype)
        {
            $cmd_params.ListSubType = $list_subtype
        }
        $this.CreateSession()
        $results = Remove-TenantAllowBlockListItems @cmd_params
        $this.DisconnectSession()
        return $results
        <#
            .DESCRIPTION
            Use the New-TenantAllowBlockListItems cmdlet to add new entries to the Tenant Allow/Block Lists for your organization.
            This cmdlet returns all new entries created, details about them, and their status

            .LINK
            https://learn.microsoft.com/en-us/powershell/module/exchange/remove-tenantallowblocklistitems?view=exchange-ps

        #>
    }

    [PSObject]
    EXOGetTenantAllowBlockList(
            [string]$entry,
            [string]$list_type,
            [string]$list_subtype,
            [string]$action,
            [bool]$no_expiration,
            [string]$expiration_date
    )
    {
        $results = ""
        try {
            $cmd_params = @{ }
            if ($entry)
            {
                $cmd_params.Entry = $entry
            }
            if ($list_type)
            {
                $cmd_params.ListType = $list_type
            }
            if ($list_subtype)
            {
                $cmd_params.ListSubType = $list_subtype
            }
            if ($no_expiration)
            {
                $cmd_params.NoExpiration = $null
            }
            if ($expiration_date)
            {
                $cmd_params.ExpirationDate = $expiration_date
            }
            if ($action -eq "Block")
            {
                $cmd_params.Block = $null
            }
            if ($action -eq "Allow")
            {
                $cmd_params.Allow = $null
            }
            $this.CreateSession()
            $results = Get-TenantAllowBlockListItems @cmd_params
        }
        finally {
            $this.DisconnectSession()
        }
        return $results
        <#
            .DESCRIPTION
            Use the Get-TenantAllowBlockListItems cmdlet to retrieve current entries in the Tenant Allow/Block Lists for your organization.
            This cmdlet returns current entries and details about them.

            .LINK
            https://learn.microsoft.com/en-us/powershell/module/exchange/get-tenantallowblocklistitems?view=exchange-ps

        #>
    }
    [psobject]GetJunkRules([string]$mailbox) {
        $response = ''
        try {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $cmd_params = @{
                "Identity" = $mailbox
            }
            $response = Get-MailboxJunkEmailConfiguration @cmd_params
        }
        finally {
            # Close session to remote
            $this.DisconnectSession()
        }
        return $response
        <#
            .DESCRIPTION
            Get junk rules in mailbox.

            .PARAMETER mailbox
            Mailbox ID.

            .EXAMPLE
            $client.GetJunkRules("test@microsoft.com")

            .OUTPUTS
            psobject - Raw response.

            .LINK
            https://docs.microsoft.com/en-us/powershell/module/exchange/get-mailboxjunkemailconfiguration?view=exchange-ps
        #>
    }

    SetJunkRules([string]$mailbox, [string[]]$add_blocked_senders_and_domains, [string[]]$remove_blocked_senders_and_domains,
        [string[]]$add_trusted_senders_and_domains, [string[]]$remove_trusted_senders_and_domains,
        [bool]$trusted_lists_only, [bool]$contacts_trusted, [bool]$enabled) {
        try {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $cmd_params = @{
                "Identity"                 = $mailbox
                "TrustedListsOnly"         = $trusted_lists_only
                "ContactsTrusted"          = $contacts_trusted
                "Enabled"                  = $enabled
                "Confirm"                  = $false
            }
            $blocked_senders_and_domains = CreateAddAndRemoveSections $add_blocked_senders_and_domains $remove_blocked_senders_and_domains
            if ($blocked_senders_and_domains -ne $null){
                $cmd_params["BlockedSendersAndDomains"] = $blocked_senders_and_domains
            }
            $trusted_senderns_and_domains = CreateAddAndRemoveSections $add_trusted_senders_and_domains $remove_trusted_senders_and_domains
            if ($trusted_senderns_and_domains -ne $null){
                $cmd_params["TrustedSendersAndDomains"] = $trusted_senderns_and_domains
            }
            Set-MailboxJunkEmailConfiguration @cmd_params
        }
        finally {
            # Close session to remote
            $this.DisconnectSession()
        }
        <#
            .DESCRIPTION
            Set junk rules in mailbox.

            .PARAMETER mailbox
            Mailbox ID.

            .PARAMETER add_blocked_senders_and_domains
            Blocked senders and domains (Comma separated).

            .PARAMETER remove_blocked_senders_and_domains
            Blocked senders and domains (Comma separated) to remove.

            .PARAMETER add_trusted_senders_and_domains
            Trusted senders and domains (Comma separated).

            .PARAMETER remove_trusted_senders_and_domains
            Trusted senders and domains (Comma separated) to remove.

            .PARAMETER trusted_lists_only
            Whether to trust only list of defined in trusted lists.

            .PARAMETER contacts_trusted
            Whether contacts trusted by default.

            .PARAMETER enabled
            Whether junk rule is enabled.

            .OUTPUTS
            psobject - Raw response.

            .LINK
            https://docs.microsoft.com/en-us/powershell/module/exchange/set-mailboxjunkemailconfiguration?view=exchange-ps
        #>
    }

    SetGlobalJunkRules([string]$mailbox, [string[]]$add_blocked_senders_and_domains, [string[]]$remove_blocked_senders_and_domains,
        [string[]]$add_trusted_senders_and_domains, [string[]]$remove_trusted_senders_and_domains,
        [bool]$trusted_lists_only, [bool]$contacts_trusted, [bool]$enabled) {
        try {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $cmd_params = @{
                "TrustedListsOnly"         = $trusted_lists_only
                "ContactsTrusted"          = $contacts_trusted
                "Enabled"                  = $enabled
                "Confirm"                  = $false
            }
            $blocked_senders_and_domains = CreateAddAndRemoveSections $add_blocked_senders_and_domains $remove_blocked_senders_and_domains
            if ($blocked_senders_and_domains -ne $null){
                $cmd_params["BlockedSendersAndDomains"] = $blocked_senders_and_domains
            }
            $trusted_senderns_and_domains = CreateAddAndRemoveSections $add_trusted_senders_and_domains $remove_trusted_senders_and_domains
            if ($trusted_senderns_and_domains -ne $null){
                $cmd_params["TrustedSendersAndDomains"] = $trusted_senderns_and_domains
            }
            Get-Mailbox -RecipientTypeDetails UserMailbox -ResultSize Unlimited | ForEach-Object {
                Set-MailboxJunkEmailConfiguration -Identity $_.Name @cmd_params
            }
        }
        finally {
            # Close session to remote
            $this.DisconnectSession()
        }
        <#
            .DESCRIPTION
            Set junk rules in all managed accounts.

            .PARAMETER add_blocked_senders_and_domains
            Blocked senders and domains (Comma separated).

            .PARAMETER remove_blocked_senders_and_domains
            Blocked senders and domains (Comma separated) to remove.

            .PARAMETER add_trusted_senders_and_domains
            Trusted senders and domains (Comma separated).

            .PARAMETER remove_trusted_senders_and_domains
            Trusted senders and domains (Comma separated) to remove.

            .PARAMETER trusted_lists_only
            Whether to trust only list of defined in trusted lists.

            .PARAMETER contacts_trusted
            Whether contacts trusted by default.

            .PARAMETER enabled
            Whether junk rule is enabled.

            .PARAMETER mailbox
            Mailbox ID.

            .OUTPUTS
            psobject - Raw response.

            .LINK
            https://docs.microsoft.com/en-us/exchange/antispam-and-antimalware/antispam-protection/configure-antispam-settings?view=exchserver-2019
        #>
    }

    [PSObject]GetMessageTrace([string[]]$sender_address, [string[]]$recipient_address, [string]$from_ip, [string]$to_ip, [string[]]$message_id,
        [string]$message_trace_id, [int32]$page, [int32]$page_size, [String]$start_date, [String]$end_date, [string]$status) {
        $response = ""
        try {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $cmd_params = @{
                "Page"             = $page
                "PageSize"         = $page_size
            }
            if ($sender_address) {
                $cmd_params.SenderAddress = $sender_address
            }
            if ($recipient_address) {
                $cmd_params.RecipientAddress = $recipient_address
            }
            if ($status) {
                $cmd_params.Status = $status
            }
            if ($start_date) {
                $cmd_params.StartDate = $start_date
                if ($end_date) {
                    $cmd_params.EndDate = $end_date
                }
                else {
                    $cmd_params.EndDate = Get-Date -UFormat "%D %I:%M %p"
                }
            }
            if ($from_ip) {
                $cmd_params.FromIP = $from_ip
            }
            if ($to_ip) {
                $cmd_params.ToIP = $to_ip
            }
            if ($message_id) {
                $cmd_params.MessageId = $message_id
            }
            if ($message_trace_id) {
                $cmd_params.MessageTraceId = $message_trace_id
            }
            $response = Get-MessageTrace @cmd_params
        }
        finally {
            # Close session to remote
            $this.DisconnectSession()
        }
        return $response
        <#
            .DESCRIPTION
            Search message data for the last 10 days.

            .PARAMETER sender_address
            The sender_address parameter filters the results by the sender's email address.

            .PARAMETER recipient_address
            The recipient_address parameter filters the results by the recipient's email address. You can specify multiple values separated by commas.

            .PARAMETER from_ip
            The from_ip parameter filters the results by the source IP address.
            For incoming messages, the value of from_ip is the public IP address of the SMTP email server that sent the message.
            For outgoing messages from Exchange Online, the value is blank.

            .PARAMETER to_ip
            The to_ip parameter filters the results by the destination IP address.
            For outgoing messages, the value of to_ip is the public IP address in the resolved MX record for the destination domain.
            For incoming messages to Exchange Online, the value is blank.

            .PARAMETER message_id
            The message_id parameter filters the results by the Message-ID header field of the message.
            This value is also known as the Client ID. The format of the Message-ID depends on the messaging server that sent the message.
            The value should be unique for each message. However, not all messaging servers create values for the Message-ID in the same way.
            Besure to include the full Message ID string (which may include angle brackets) and enclose the value in quotation marks (for example,"d9683b4c-127b-413a-ae2e-fa7dfb32c69d@DM3NAM06BG401.Eop-nam06.prod.protection.outlook.com").

            .PARAMETER message_trace_id
            The message_trace_id parameter can be used with the recipient address to uniquely identify a message trace and obtain more details.
            A message trace ID is generated for every message that's processed by the system.

            .PARAMETER page
            The page parameter specifies the page number of the results you want to view.
            Valid input for this parameter is an integer between 1 and 1000. The default value is 1.

            .PARAMETER page_size
            The page_size parameter specifies the maximum number of entries per page.
            Valid input for this parameter is an integer between 1 and 5000. The default value is 100.

            .PARAMETER start_date
            The start_date parameter specifies the start date of the date range.
            Use the short date format that's defined in the Regional Options settings on the computer where you're running the command. For example, if the computer is configured to use the short date format mm/dd/yyyy,
            enter 09/01/2018 to specify September 1, 2018. You can enter the date only, or you can enter the date and time of day.
            If you enter the date and time of day, enclose the value in quotation marks ("), for example, "09/01/2018 5:00 PM".
            Valid input for this parameter is from 10 days - now ago. The default value is 48 hours ago.

            .PARAMETER end_date
            The end_date parameter specifies the end date of the date range.
            Use the short date format that's defined in the Regional Options settings on the computer where you're running the command.
            For example, if the computer is configured to use the short date format mm/dd/yyyy, enter 09/01/2018 to specify September 1, 2018.
            You can enter the date only, or you can enter the date and time of day.
            If you enter the date and time of day, enclose the value in quotation marks ("), for example, "09/01/2018 5:00 PM".
            Valid input for this parameter is from start_date - now. The default value is now.

            .PARAMETER status
            * GettingStatus: The message is waiting for status update.
            * Failed: Message delivery was attempted and it failed or the message was filtered as spam or malware, or by transport rules.
            * Pending: Message delivery is underway or was deferred and is being retried.
            * Delivered: The message was delivered to its destination.
            * Expanded: There was no message delivery because the message was addressed to a distribution group and the membership of the distribution was expanded.
            * Quarantined: The message was quarantined.
            * FilteredAsSpam: The message was marked as spam.

            .OUTPUTS
            psobject - Raw response.

            .LINK
            https://docs.microsoft.com/en-us/powershell/module/exchange/get-messagetrace?view=exchange-ps
        #>
    }

    [PSObject]GetMessageTraceList([string[]]$sender_address, [string[]]$recipient_address, [string]$from_ip, [string]$to_ip, [string[]]$message_id,
        [string]$message_trace_id, [string]$start_date, [string]$end_date, [string[]]$status, [string]$subject, [string]$subject_filter_type,
        [string]$starting_recipient_address, [int32]$limit) {
        $response = ""
        try {
            # Create Exchange Online session
            $this.CreateSession()
            $cmd_params = @{}
            # Import and Execute a command
            if ($sender_address) {
                $cmd_params.SenderAddress = $sender_address
            }
            if ($recipient_address) {
                $cmd_params.RecipientAddress = $recipient_address
            }
            if ($status) {
                $cmd_params.Status = $status
            }
            if ($start_date) {
                $cmd_params.StartDate = $start_date
                if ($end_date) {
                    $cmd_params.EndDate = $end_date
                }
                else {
                    $cmd_params.EndDate = Get-Date -UFormat "%D %I:%M %p"
                }
            }
            if ($from_ip) {
                $cmd_params.FromIP = $from_ip
            }
            if ($to_ip) {
                $cmd_params.ToIP = $to_ip
            }
            if ($message_id) {
                $cmd_params.MessageId = $message_id
            }
            if ($message_trace_id) {
                $cmd_params.MessageTraceId = $message_trace_id
            }
            if ($subject) {
                $cmd_params.Subject = $subject
            }
            if ($subject_filter_type) {
                $cmd_params.SubjectFilterType = $subject_filter_type
            }
            if ($starting_recipient_address) {
                $cmd_params.StartingRecipientAddress = $starting_recipient_address
            }
            if ($limit) {
                $cmd_params.ResultSize = $limit
            }

            $response = Get-MessageTraceV2 @cmd_params
        }
        finally {
            # Disconnect Exchange Online session
            $this.DisconnectSession()
        }
        return $response
        <#
            .DESCRIPTION
            Search message data from the last 90 days.

            .PARAMETER sender_address
            The sender_address parameter filters the results by the sender's email address.

            .PARAMETER recipient_address
            The recipient_address parameter filters the results by the recipient's email address. You can specify multiple values separated by commas.

            .PARAMETER from_ip
            The from_ip parameter filters the results by the source IP address.
            For incoming messages, the value of from_ip is the public IP address of the SMTP email server that sent the message.
            For outgoing messages from Exchange Online, the value is blank.

            .PARAMETER to_ip
            The to_ip parameter filters the results by the destination IP address.
            For outgoing messages, the value of to_ip is the public IP address in the resolved MX record for the destination domain.
            For incoming messages to Exchange Online, the value is blank.

            .PARAMETER message_id
            The message_id parameter filters the results by the Message-ID header field of the message.
            This value is also known as the Client ID. The format of the Message-ID depends on the messaging server that sent the message.
            The value should be unique for each message. However, not all messaging servers create values for the Message-ID in the same way.
            Besure to include the full Message ID string (which may include angle brackets) and enclose the value in quotation marks (for example,"d9683b4c-127b-413a-ae2e-fa7dfb32c69d@DM3NAM06BG401.Eop-nam06.prod.protection.outlook.com").

            .PARAMETER message_trace_id
            The message_trace_id parameter can be used with the recipient address to uniquely identify a message trace and obtain more details.
            A message trace ID is generated for every message that's processed by the system.

            .PARAMETER start_date
            The start_date parameter specifies the start date of the date range.
            Use the short date format defined in the computer's Regional Options settings. For example, if the computer is configured to use the short date format mm/dd/yyyy, enter 09/01/2018 to specify September 1, 2018.
            You can enter the date only, or you can enter the date and time of day.
            If you enter the date and time of day, enclose the value in quotation marks ("), for example, "09/01/2018 5:00 PM".
            Valid input is from 10 days ago up to the current time. The default is 48 hours ago.

            .PARAMETER end_date
            The end_date parameter specifies the end date of the date range.
            Use the short date format in the computer's Regional Options settings.
            For example, if the computer is configured to use the short date format mm/dd/yyyy, enter 09/01/2018 to specify September 1, 2018.
            You can enter the date only, or you can enter the date and time of day.
            If you enter the date and time of day, enclose the value in quotation marks ("), for example, "09/01/2018 5:00 PM".
            Valid input is from start_date up to the current time. The default is the current time.

            .PARAMETER status
            * GettingStatus: The message is pending a status update.
            * Failed: The message delivery was attempted but failed, or the message was filtered as spam, malware, or by transport rules.
            * Pending: Message delivery is in progress or was deferred and is being retried
            * Delivered: The message was successfully delivered to its destination.
            * Expanded: No message was delivered because the message was sent to a distribution group; the group's membership was expanded instead.
            * Quarantined: The message was quarantined.
            * FilteredAsSpam: The message was marked as spam.

            .PARAMETER subject
            Filters results by the subject of the message. If the value contains spaces, enclose it in quotation marks (")

            .PARAMETER subject_filter_type
            The subject_filter_type parameter specifies how the value of the subject parameter is evaluated. Valid values are:
            * Contains
            * EndsWith
            * StartsWith
            It is recommend to use StartsWith or EndsWith instead of Contains whenever possible.

            .PARAMETER starting_recipient_address
            The starting_recipient_address parameter is used with the end_date parameter to query subsequent data while avoiding duplicates.
            For subsequent queries, use the Recipient address and Received Time from the last record of the previous results as the values for starting_recipient_address and end_date, respectively.

            .PARAMETER limit
            The limit parameter specifies the maximum number of results to return.
            Valid values are 1 to 5000. The default is 1000.

            .OUTPUTS
            [PSObject] – Returns the raw response.

            .LINK
            https://docs.microsoft.com/en-us/powershell/module/exchange/get-messagetracev2?view=exchange-ps
        #>
    }

    [PSObject]GetFederationTrust(
            [string]$domain_controller,
            [string]$identity
    )
    {
        $response = ""
        try {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $cmd_params = @{}
            if ($identity) {
                $cmd_params.Identity = $identity
            }
            if ($domain_controller) {
                $cmd_params.DomainController = $domain_controller
            }
            $response = Get-FederationTrust @cmd_params
        }
        finally {
            $this.DisconnectSession()
        }
        return $response
        <#
        .DESCRIPTION
        Use the Get-FederationTrust cmdlet to view the federation trust configured for the Exchange organization.

        .PARAMETER domain_controller
        This parameter is available only in on-premises Exchange.
        The DomainController parameter specifies the domain controller that's used by this
        cmdlet to read data from or write data to Active Directory. You identify the domain
        controller by its fully qualified domain name (FQDN).
        For example, dc01.contoso.com.

        .PARAMETER identity
        The Identity parameter specifies a federation trust ID. If not specified, the cmdlet returns
        all federation trusts configured for the Exchange organization.

        .EXAMPLE
        GetFederationTrust("dc01.contoso.com", "1254y894-feae-9yn7-a3e1-f2483a154tft")

        .OUTPUTS
        PSObject - Raw response

        .LINK
        https://docs.microsoft.com/en-us/powershell/module/exchange/get-federationtrust?view=exchange-ps
    #>
    }


    [PSObject]GetFederationConfiguration(
        [string]$domain_controller,
        [string]$identity,
        [bool]$include_extended_domain_info
    ) {
        $response = ""
        try {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $cmd_params = @{}
            if ($identity) {
                $cmd_params.Identity = $identity
            }
            if ($domain_controller) {
                $cmd_params.DomainController = $domain_controller
            }
            if ($include_extended_domain_info) {
                $cmd_params.IncludeExtendedDomainInfo = $include_extended_domain_info
            }
            $response = Get-FederatedOrganizationIdentifier @cmd_params
        }
        finally {
            $this.DisconnectSession()
        }
        return $response
        <#
        .DESCRIPTION
        Use the Get-FederatedOrganizationIdentifier cmdlet to retrieve the Exchange organization's federated
        organization identifier and related details, such as federated domains, organization contact and status.

        .PARAMETER domain_controller
        This parameter is available only in on-premises Exchange.
        The DomainController parameter specifies the domain controller that's used by this
        cmdlet to read data from or write data to Active Directory. You identify the domain
        controller by its fully qualified domain name (FQDN).
        For example, dc01.contoso.com.

        .PARAMETER identity
        The Identity parameter specifies a federation trust ID. If not specified, the cmdlet returns
        all federation trusts configured for the Exchange organization.

        .PARAMETER include_extended_domain_info
        The IncludeExtendedDomainInfo switch specifies that the command query Microsoft Federation Gateway for the status of each
        accepted domain that's federated. The status is returned with each domain in the Domains property.

        .EXAMPLE
        GetFederationConfiguration("dc01.contoso.com", "1254y894-feae-9yn7-a3e1-f2483a154tft", $true)

        .OUTPUTS
        PSObject - Raw response

        .LINK
        https://docs.microsoft.com/en-us/powershell/module/exchange/get-federatedorganizationidentifier?view=exchange-ps
        #>
    }
    [PSObject]GetUser(
        [string]$identity,
        [string]$organizational_unit,
        [int]$limit
    ) {
        $response = ""
        try
        {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $cmd_params = @{ }
            if ($identity)
            {
                $cmd_params.Identity = $identity
            }
            if ($organizational_unit)
            {
                $cmd_params.OrganizationalUnit = $organizational_unit
            }
            if ($limit -gt 0)
            {
                $response = Get-User @cmd_params -ResultSize $limit -WarningAction:SilentlyContinue
            }
            else
            {
                $response = Get-User @cmd_params -ResultSize Unlimited
            }
        } finally {
            $this.DisconnectSession()
        }
        return $response
        <#
        .DESCRIPTION
        Use the Get-User command to view existing user objects in your organization.

        .PARAMETER identity
        The Identity parameter the user that you want to view. You can use any value that uniquely identifies the user

        .PARAMETER orgranizational_unit
        The OrganizationalUnit parameter filters the results based on the object's location in Active Directory.

        .EXAMPLE
        GetUser("user@microsoft.com")

        .OUTPUTS
        PSObject - Raw response

        .LINK
        https://docs.microsoft.com/en-us/powershell/module/exchange/get-user?view=exchange-ps        #>
    }
    [PSObject]GetMailboxAuditBypassAssociation(
        [string]$identity,
        [string]$domain_controller,
        [int]$limit
    )
    {
        $response = ""
        try {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $cmd_params = @{ }
            if ($identity) {
                $cmd_params.Identity = $identity
            }
            if ($domain_controller) {
                $cmd_params.DomainController = $domain_controller
            }
            if ($limit -gt 0){
                $cmd_params.ResultSize = $limit
            }
            $response = Get-MailboxAuditBypassAssociation @cmd_params -WarningAction:SilentlyContinue
        } finally {
            $this.DisconnectSession()
        }
        return $response
        <#
        .DESCRIPTION
        Retrieve information about the AuditBypassEnabled property value for user accounts
        (on-premises Exchange and the cloud) and computer accounts (on-premises Exchange only).

        .PARAMETER identity
        The Identity parameter the user that you want to view. You can use any value that uniquely identifies the user

        .PARAMETER domain_controller
        The DomainController parameter specifies the domain controller that's used by this cmdlet to read data from
        or write data to Active Directory. You identify the domain controller by its fully qualified domain name (FQDN).

        .EXAMPLE

        .OUTPUTS
        PSObject - Raw response

        .LINK
        https://docs.microsoft.com/en-us/powershell/module/exchange/get-mailboxauditbypassassociation?view=exchange-ps
        #>
    }

    [PSCustomObject]GetRemoteDomain(
        [string]$domain_controller,
        [string]$identity
    ) {
        $response = ""
        try {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $cmd_params = @{}
            if ($identity) {
                $cmd_params.Identity = $identity
            }
            if ($domain_controller) {
                $cmd_params.DomainController = $domain_controller
            }
            return Get-RemoteDomain @cmd_params -WarningAction:SilentlyContinue
        }
        finally {
            $this.DisconnectSession()
        }
        return $response
        <#
        .DESCRIPTION
        Use the Get-RemoteDomain cmdlet to view the configuration information for the remote domains configured in
        your organization.

        .PARAMETER domain_controller
        This parameter is available only in on-premises Exchange.
        The DomainController parameter specifies the domain controller that's used by this
        cmdlet to read data from or write data to Active Directory. You identify the domain
        controller by its fully qualified domain name (FQDN).
        For example, dc01.contoso.com.

        .PARAMETER identity
        The Identity parameter specifies a federation trust ID. If not specified, the cmdlet returns
        all federation trusts configured for the Exchange organization.

        .EXAMPLE
        GetRemoteDomain("1254y894-feae-9yn7-a3e1-f2483a154tft")

        .OUTPUTS
        PSObject - Raw response

        .LINK
        https://docs.microsoft.com/en-us/powershell/module/exchange/get-remotedomain?view=exchange-ps
        #>
    }

    [PSObject]GetRules(
        [string]$mailbox,
        [int]$limit
    )
    {
        $response = ""
        try {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $cmd_params = @{ }
            if ($mailbox) {
                $cmd_params.Mailbox = $mailbox
            }

            if ($limit -gt 0){
                $cmd_params.ResultSize = $limit
            }
            $response = Get-InboxRule @cmd_params -WarningAction:SilentlyContinue
        } finally {
            $this.DisconnectSession()
        }
        return $response
        <#
        .DESCRIPTION
        Retrieve information about the Inbox rule properties.

        .PARAMETER mailbox
        The mailox that contains the Inbox rules

        .PARAMETER limit
        The amount of rules to return.

        .EXAMPLE

        .OUTPUTS
        PSObject - Raw response

        .LINK
        https://learn.microsoft.com/en-us/powershell/module/exchange/get-inboxrule?view=exchange-ps
        #>
    }

    [PSObject]GetRule(
        [string]$mailbox,
        [string]$identity
    )
    {
        $response = ""
        try {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $cmd_params = @{ }
            if ($mailbox) {
                $cmd_params.Mailbox = $mailbox
            }

            if ($identity) {
                $cmd_params.Identity = $identity
            }

            $response = Get-InboxRule @cmd_params -WarningAction:SilentlyContinue

        } finally {
            $this.DisconnectSession()
        }
        return $response
        <#
        .DESCRIPTION
        Retrieve information about the Inbox rule properties.

        .PARAMETER mailbox
        The mailox that contains the Inbox rule

        .PARAMETER identity
        The Identity parameter the inbox rule that you want to view.

        .EXAMPLE

        .OUTPUTS
        PSObject - Raw response

        .LINK
        https://learn.microsoft.com/en-us/powershell/module/exchange/get-inboxrule?view=exchange-ps
        #>
    }

    [PSObject]RemoveRule(
        [string]$mailbox,
        [string]$identity
    )
    {
        $response = ""
        try {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $cmd_params = @{ }
            if ($mailbox) {
                $cmd_params.Mailbox = $mailbox
            }

            if ($identity) {
                $cmd_params.Identity = $identity
            }
            $response = Remove-InboxRule -Confirm:$false @cmd_params -WarningAction:SilentlyContinue
        } finally {
            $this.DisconnectSession()
        }
        return $response
        <#
        .DESCRIPTION
        Remove an Inbox rule.

        .PARAMETER mailbox
        The mailbox that contains the Inbox rule

        .PARAMETER identity
        The Identity parameter the inbox rule that you want to remove.

        .EXAMPLE

        .OUTPUTS
        PSObject - Raw response

        .LINK
        https://learn.microsoft.com/en-us/powershell/module/exchange/remove-inboxrule?view=exchange-ps
        #>
    }

    [PSObject]DisableRule(
    [string]$mailbox,
    [string]$identity
    )
    {
        $response = ""
        try {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $cmd_params = @{ }
            if ($mailbox) {
                $cmd_params.Mailbox = $mailbox
            }

            if ($identity) {
                $cmd_params.Identity = $identity
            }
            $response = Disable-InboxRule -Confirm:$false @cmd_params -WarningAction:SilentlyContinue
        } finally {
            $this.DisconnectSession()
        }
        return $response
        <#
        .DESCRIPTION
        Disable an existing inbox rule in a given mailbox.

        .PARAMETER mailbox
        The mailbox that contains the Inbox rule.

        .PARAMETER identity
        Specifies the Inbox rule that you want to disable.

        .EXAMPLE
        Disable-InboxRule -Identity "MoveAnnouncements" -Mailbox "example@example.com"

        .OUTPUTS
        PSObject - Raw response

        .LINK
        https://learn.microsoft.com/en-us/powershell/module/exchange/disable-inboxrule?view=exchange-ps
        #>
    }

    [PSObject]EnableRule(
    [string]$mailbox,
    [string]$identity
    )
    {
        $response = ""
        try {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $cmd_params = @{ }
            if ($mailbox) {
                $cmd_params.Mailbox = $mailbox
            }

            if ($identity) {
                $cmd_params.Identity = $identity
            }
            $response = Enable-InboxRule @cmd_params -WarningAction:SilentlyContinue
        } finally {
            $this.DisconnectSession()
        }
        return $response
        <#
        .DESCRIPTION
        Enable an existing inbox rule in a given mailbox.

        .PARAMETER mailbox
        The mailbox that contains the Inbox rule.

        .PARAMETER identity
        Specifies the Inbox rule that you want to enable.

        .EXAMPLE
        Enable-InboxRule "Move To Junk Mail" -Mailbox "User 1"

        .OUTPUTS
        PSObject - Raw response

        .LINK
        https://learn.microsoft.com/en-us/powershell/module/exchange/enable-inboxrule?view=exchange-ps
        #>
    }

    [PSObject]ListMailFlowRules([int]$limit)
    {
        $response = ""
        try {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $cmd_params = @{ }
            if ($limit -gt 0){
                $cmd_params.ResultSize = $limit
            }
            $response = Get-TransportRule @cmd_params -WarningAction:SilentlyContinue
        } finally {
            $this.DisconnectSession()
        }
        return $response
        <#
        .DESCRIPTION
        List all mail flow rules (transport rules) in the organization.

        .PARAMETER limit
        The amount of mail flow rules to return.

        .EXAMPLE
        Get-TransportRule

        .OUTPUTS
        PSObject - Raw response

        .LINK
        https://learn.microsoft.com/en-us/powershell/module/exchange/get-transportrule?view=exchange-ps
        #>
    }

    [PSObject]GetMailFlowRule([string]$identity)
    {
        $response = ""
        try {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $cmd_params = @{ }
            if ($identity) {
                $cmd_params.Identity = $identity
            }
            $response = Get-TransportRule @cmd_params -WarningAction:SilentlyContinue
        } finally {
            $this.DisconnectSession()
        }
        return $response
        <#
        .DESCRIPTION
        Get a mail flow rule (transport rules) in the organization.

        .PARAMETER identity
        Specifies the rule that you want to view.

        .EXAMPLE
        Get-TransportRule "Ethical Wall - Sales and Brokerage Departments" | Format-List

        .OUTPUTS
        PSObject - Raw response

        .LINK
        https://learn.microsoft.com/en-us/powershell/module/exchange/get-transportrule?view=exchange-ps
        #>
    }

    [PSObject]CreateMailFlowRule([hashtable]$cmd_params)
    {
        $response = ""
        try {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $response = New-TransportRule @cmd_params -WarningAction:SilentlyContinue
        } finally {
            $this.DisconnectSession()
        }
        return $response
        <#
        .DESCRIPTION
        Create a mail flow rule (transport rule) in the organization.

        .PARAMETER cmd_params
        A hashtable of parameters (already mapped to the New-TransportRule parameter names) to create the rule with.

        .EXAMPLE
        New-TransportRule -Name "Ethical Wall" -RejectMessageReasonText "Not allowed"

        .OUTPUTS
        PSObject - Raw response

        .LINK
        https://learn.microsoft.com/en-us/powershell/module/exchange/new-transportrule?view=exchange-ps
        #>
    }

    [PSObject]UpdateMailFlowRule([hashtable]$cmd_params)
    {
        $response = ""
        try {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $response = Set-TransportRule @cmd_params -WarningAction:SilentlyContinue
        } finally {
            $this.DisconnectSession()
        }
        return $response
        <#
        .DESCRIPTION
        Modify an existing mail flow rule (transport rule) in the organization.

        .PARAMETER cmd_params
        A hashtable of parameters (already mapped to the Set-TransportRule parameter names) to modify the rule with. Must include the Identity of the rule to modify.

        .EXAMPLE
        Set-TransportRule -Identity "Sales Team Disclaimer" -Priority 1

        .OUTPUTS
        PSObject - Raw response (Set-TransportRule returns no output on success)

        .LINK
        https://learn.microsoft.com/en-us/powershell/module/exchange/set-transportrule?view=exchange-ps
        #>
    }

    [PSObject]RemoveMailFlowRule([string]$identity)
    {
        $response = ""
        try {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $cmd_params = @{ }
            if ($identity) {
                $cmd_params.Identity = $identity
            }
            $response = Remove-TransportRule -Confirm:$false @cmd_params -WarningAction:SilentlyContinue
        } finally {
            $this.DisconnectSession()
        }
        return $response
        <#
        .DESCRIPTION
        Remove a mail flow rule (transport rule) from the organization.

        .PARAMETER identity
        Specifies the rule that you want to remove.

        .EXAMPLE
        Remove-TransportRule -Identity "Redirect messages from example1@example.com to example2@example.com"

        .OUTPUTS
        PSObject - Raw response

        .LINK
        https://learn.microsoft.com/en-us/powershell/module/exchange/remove-transportrule?view=exchange-ps
        #>
    }

    [PSObject]DisableMailFlowRule([string]$identity)
    {
        $response = ""
        try {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $cmd_params = @{ }
            if ($identity) {
                $cmd_params.Identity = $identity
            }
            $response = Disable-TransportRule -Confirm:$false @cmd_params -WarningAction:SilentlyContinue
        } finally {
            $this.DisconnectSession()
        }
        return $response
        <#
        .DESCRIPTION
        Disable a mail flow rule (transport rule) in the organization.

        .PARAMETER identity
        Specifies the rule that you want to disable.

        .EXAMPLE
        Disable-TransportRule -Identity "Sales Disclaimer"

        .OUTPUTS
        PSObject - Raw response

        .LINK
        https://learn.microsoft.com/en-us/powershell/module/exchange/disable-transportrule?view=exchange-ps
        #>
    }

    [PSObject]EnableMailFlowRule([string]$identity)
    {
        $response = ""
        try {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $cmd_params = @{ }
            if ($identity) {
                $cmd_params.Identity = $identity
            }
            $response = Enable-TransportRule @cmd_params -WarningAction:SilentlyContinue
        } finally {
            $this.DisconnectSession()
        }
        return $response
        <#
        .DESCRIPTION
        Enable a mail flow rule (transport rule) in the organization.

        .PARAMETER identity
        Specifies the rule that you want to enable.

        .EXAMPLE
        Enable-TransportRule -Identity "Disclaimer-Finance"

        .OUTPUTS
        PSObject - Raw response

        .LINK
        https://learn.microsoft.com/en-us/powershell/module/exchange/enable-transportrule?view=exchange-ps
        #>
    }

    [PSObject]DisableMailForwarding([string]$identity)
    {
        $response = ""
        try {
            # Establish session to remote
            $this.CreateSession()
            # Import and Execute command
            $cmd_params = @{ }
            if ($identity) {
                $cmd_params.Identity = $identity
            }
            $response = Set-Mailbox @cmd_params -ForwardingAddress $null -ForwardingSmtpAddress $null -DeliverToMailboxAndForward $false -WarningAction:SilentlyContinue
        } finally {
            $this.DisconnectSession()
        }
        return $response
        <#
        .DESCRIPTION
        Disable mail forwarding for a given user.

        .PARAMETER identity
        Specifies the mailbox that you want to modify.

        .EXAMPLE
        Set-Mailbox -Identity "John Woods" -DeliverToMailboxAndForward $true -ForwardingSMTPAddress example@example.com

        .OUTPUTS
        PSObject - Raw response

        .LINK
        https://learn.microsoft.com/en-us/powershell/module/exchange/set-mailbox?view=exchange-ps
        #>
    }
}

function Remove-EmptyItems {
    param (
        [PSObject]$inputObject
    )

    $newDict = @{}

    foreach ($property in $inputObject.PSObject.Properties) {
        $value = $property.Value

        # Check if the value is not null, whitespace, or an empty collection
        if (-not [string]::IsNullOrWhiteSpace($value)) {
            # Check if it's an IEnumerable (like array or list) and if the collection is not empty
            if ($value -is [System.Collections.IEnumerable] -and -not ($value -is [string]) -and $value.Count -eq 0) {
                continue
            }

            # If it's not an empty collection, add it to the new dictionary
            $newDict[$property.Name] = $value
        }
    }

    return $newDict
}

function GetEXORecipientCommand
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $identity = $kwargs.identity
    $limit = $kwargs.limit -as [int]
    $raw_response = $client.GetEXORecipient($identity, $limit)
    $human_readable = TableToMarkdown $raw_response "Results of $command"
    $entry_context = @{ "$script:INTEGRATION_ENTRY_CONTEXT.Recipient(obj.Guid === val.Guid)" = $raw_response }
    Write-Output $human_readable, $entry_context, $raw_response
}

function GetEXORecipientPermissionCommand
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $identity = $kwargs.identity
    $limit = $kwargs.limit -as [int]
    $raw_response = $client.GetEXORecipientPermission($identity, $limit)
    $human_readable = TableToMarkdown $raw_response "Results of $command"
    $entry_context = @{ "$script:INTEGRATION_ENTRY_CONTEXT.RecipientPermission(obj.Identity === val.Identity)" = $raw_response }
    Write-Output $human_readable, $entry_context, $raw_response
}

function GetEXOMailBoxPermissionCommand
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $identity = $kwargs.identity
    $raw_response = $client.GetEXOMailBoxPermission($identity)
    $human_readable = TableToMarkdown $raw_response "Results of $command"
    $entry_context = @{
        "$script:INTEGRATION_ENTRY_CONTEXT.MailboxPermission(obj.Identity === val.Identity)" = @{
            "Identity" = $identity
            "Permission" = $raw_response
        }
    }
    Write-Output $human_readable, $entry_context, $raw_response
}

function GetEXOMailBoxCommand
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $identity = $kwargs.identity
    $limit = $kwargs.limit -as [int]
    $raw_response = $client.GetEXOMailBox($identity, $kwargs.property_sets, $limit)
    $human_readable = TableToMarkdown $raw_response "Results of $command"
    $entry_context = @{
        "$script:INTEGRATION_ENTRY_CONTEXT.Mailbox(obj.Guid === val.Guid)" = $raw_response }
    Write-Output $human_readable, $entry_context, $raw_response
}

function GetEXOCASMailboxCommand
{
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $identity = $kwargs.identity
    $organizational_unit = $kwargs.organizational_unit
    $primary_smtp_address = $kwargs.primary_smtp_address
    $user_principal_name = $kwargs.user_principal_name
    $limit = $kwargs.limit -as [int]
    $raw_response = $client.GetEXOCASMailbox(
            $identity, $organizational_unit, $primary_smtp_address, $user_principal_name, $limit
    )
    $human_readable = TableToMarkdown $raw_response "Results of $command"
    $entry_context = @{ "$script:INTEGRATION_ENTRY_CONTEXT.CASMailbox(obj.Guid === val.Guid)" = $raw_response }
    Write-Output $human_readable, $entry_context, $raw_response
}

function EXONewTenantAllowBlockListCommand
{
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $entries = $kwargs.entries
    $list_type = $kwargs.list_type
    $list_subtype = $kwargs.list_subtype
    $action = $kwargs.action
    $notes = $kwargs.notes
    $no_expiration = if ($kwargs.no_expiration -eq "true") { $true } else { $false }
    $expiration_date = $kwargs.expiration_date
    $raw_response = $client.EXONewTenantAllowBlockList(
        $entries, $list_type, $list_subtype, $action, $notes, $no_expiration, $expiration_date
    )
    if($raw_response -eq $null){
        Write-Output "No Tenant Allow/Block List items were found."
    }
    else{
        $human_readable = TableToMarkdown $raw_response "Results of $command"
        $entry_context = @{ "$script:INTEGRATION_ENTRY_CONTEXT.NewTenantBlocks" = $raw_response }
        Write-Output $human_readable, $entry_context, $raw_response
    }

}

function EXOGetTenantAllowBlockListCommand
{
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $entry = $kwargs.entry
    $list_type = $kwargs.list_type
    $list_subtype = $kwargs.list_subtype
    $action = $kwargs.action
    $no_expiration = if ($kwargs.no_expiration -eq "true") { $true } else { $false }
    $expiration_date = $kwargs.expiration_date
    $raw_response = $client.EXOGetTenantAllowBlockList(
        $entry, $list_type, $list_subtype, $action, $no_expiration, $expiration_date
    )
    if($raw_response -eq $null){
        Write-Output "No Tenant Allow/Block List items were found."
    }
    else{
        $human_readable = TableToMarkdown $raw_response "Results of $command"
        $entry_context = @{ "$script:INTEGRATION_ENTRY_CONTEXT.CurrentTenantBlocks" = $raw_response }
        Write-Output $human_readable, $entry_context, $raw_response
    }
}

function EXOCountTenantAllowBlockListCommand
{
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $list_type = $kwargs.list_type
    $list_subtype = $kwargs.list_subtype
    $m = $client.EXOGetTenantAllowBlockList($null, $list_type, $list_subtype, $null, $null, $null) | Measure-Object
    $raw_response = [PSCustomObject]@{
        ListType = $list_type
        ListSubType = $list_subtype
        Count = $m.Count
    }
    if($raw_response -eq $null){
        Write-Output "No Tenant Allow/Block List items were found."
    }
    else{
        $human_readable = TableToMarkdown $raw_response "Results of $command"
        $entry_context = @{ "$script:INTEGRATION_ENTRY_CONTEXT.CurrentListCount" = $raw_response }
        Write-Output $human_readable, $entry_context, $raw_response
    }

}

function EXORemoveTenantAllowBlockListCommand
{
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $entries = $kwargs.entries
    $ids = $kwargs.ids
    $list_type = $kwargs.list_type
    $list_subtype = $kwargs.list_subtype
    if ($entries -and $ids)
    {
        ReturnError "Error: Please provide either entries by value OR IDs, not both."
    }
    $raw_response = $client.EXORemoveTenantAllowBlockList(
        $entries, $ids, $list_type, $list_subtype
    )
    if($raw_response -eq $null){
        Write-Output "No Tenant Allow/Block List items were found."
    }
    else{
        $human_readable = TableToMarkdown $raw_response "Results of $command"
        $entry_context = @{ "$script:INTEGRATION_ENTRY_CONTEXT.RemovedTenantBlocks" = $raw_response }
        Write-Output $human_readable, $entry_context, $raw_response
    }

}

function EXOExportQuarantineMessageCommand
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $identities = $kwargs.identities
    $identity = $kwargs.identity
    $compress_output = if ($kwargs.compress_output -eq "true") { $true } else { $false }
    $entity_type = $kwargs.entity_type
    $force_conversion_to_mime = if ($kwargs.force_conversion_to_mime -eq "true") { $true } else { $false }
    $password = $kwargs.password
    $reason_for_export = $kwargs.reason_for_export
    $recipient_address = $kwargs.recipient_address

    $raw_response = $client.EXOExportQuarantineMessage(
        $identities,
        $identity,
        $compress_output,
        $entity_type,
        $force_conversion_to_mime,
        $password,
        $reason_for_export,
        $recipient_address
    )

    $human_readable = TableToMarkdown $raw_response "Results of $command"
    $entry_context = @{ "$script:INTEGRATION_ENTRY_CONTEXT.ExportQuarantineMessage(obj.Identity === val.Identity)" = $raw_response }
    Write-Output $human_readable, $entry_context, $raw_response
}

function EXOGetQuarantineMessageCommand {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory)]$client,
        [hashtable]$kwargs
    )

    $params = @{
        Identity = $kwargs.identity
        EntityType = $kwargs.entity_type
        RecipientAddress = $kwargs.recipient_address
        SenderAddress = $kwargs.sender_address
        Direction = $kwargs.direction
        Domain = $kwargs.domain
        EndExpiresDate = $kwargs.end_expires_date
        EndReceivedDate = $kwargs.end_received_date
        IncludeMessagesFromBlockedSenderAddress = if ($kwargs.include_messages_from_blocked_sender_address -eq "true") { $true } else { $false }
        MessageId = $kwargs.message_id
        MyItems = if ($kwargs.my_items -eq "true") { $true } else { $false }
        Page = $kwargs.page
        PageSize = $kwargs.page_size
        PolicyName = $kwargs.policy_name
        PolicyTypes = ArgToList $kwargs.policy_types
        QuarantineTypes = ArgToList $kwargs.quarantine_types
        RecipientTag = $kwargs.recipient_tag
        ReleaseStatus = $kwargs.release_status
        Reported = if ($kwargs.reported -eq "true") { $true } else { $false }
        StartExpiresDate = $kwargs.start_expires_date
        StartReceivedDate = $kwargs.start_received_date
        Subject = $kwargs.subject
        Type = $kwargs.type
    }

    $client_response = $client.EXOGetQuarantineMessage($params)
    
    # Ensure raw_response is always an array, but handle null properly
    if ($null -eq $client_response) {
        $raw_response = @()
    } else {
        $raw_response = @($client_response)
    }

    # Process all items using foreach and collect results efficiently
    $newResults = @(foreach ($item in $raw_response) {
        if ($null -ne $item) {
            Remove-EmptyItems -inputObject $item
        }
    })

    # Ensure $newResults is passed correctly to formatting
    $human_readable = TableToMarkdown $newResults "Results of $command"
    $entry_context = @{ "$script:INTEGRATION_ENTRY_CONTEXT.GetQuarantineMessage(obj.Identity === val.Identity)" = $raw_response }
    
    Write-Output $human_readable, $entry_context, $raw_response
}


function EXOReleaseQuarantineMessageCommand
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )

    $user = $kwargs.user
    $identities = $kwargs.identities
    $identity = $kwargs.identity
    $release_to_all = if ($kwargs.release_to_all -eq "true") { $true } else { $false }
    $allow_sender = if ($kwargs.allow_sender -eq "true") { $true } else { $false }
    $entity_type = $kwargs.entity_type
    $force = if ($kwargs.force -eq "true") { $true } else { $false }
    $report_false_positive = if ($kwargs.report_false_positive -eq "true") { $true } else { $false }
    $action_type = $kwargs.action_type

    $result = $client.EXOReleaseQuarantineMessage(
        $user,
        $identities,
        $identity,
        $release_to_all,
        $allow_sender,
        $entity_type,
        $force,
        $report_false_positive,
        $action_type
    )

    $raw_response = @{}
    $human_readable = $identities ?
    "The following messages have been sent for release from quarantine: $identities" :
    ($identity ?
        "The message with identity $identity has been sent for release from quarantine." :
        "No identities were provided for release from quarantine.");
    $entry_context = @{}
    Write-Output $human_readable, $entry_context, $raw_response
}

function GetJunkRulesCommand([ExchangeOnlinePowershellV3Client]$client, [hashtable]$kwargs) {
    $raw_response = $client.GetJunkRules($kwargs.mailbox)
    $md_columns = $raw_response | Select-Object -Property BlockedSendersAndDomains, TrustedSendersAndDomains, ContactsTrusted, TrustedListsOnly, Enabled
    $human_readable = TableToMarkdown $md_columns  "$script:INTEGRATION_NAME - '$($kwargs.mailbox)' Junk rules"
    $entry_context = ParseJunkRulesToEntryContext $raw_response $kwargs.mailbox

    return $human_readable, $entry_context, $raw_response
}

function SetJunkRulesCommand([ExchangeOnlinePowershellV3Client]$client, [hashtable]$kwargs) {
    # Parse arguments
    $add_blocked_senders_and_domains = ArgToList $kwargs.add_blocked_senders_and_domains
    $remove_blocked_senders_and_domains = ArgToList $kwargs.remove_blocked_senders_and_domains
    $add_trusted_senders_and_domains = ArgToList $kwargs.add_trusted_senders_and_domains
    $remove_trusted_senders_and_domains = ArgToList $kwargs.remove_trusted_senders_and_domains
    if ($kwargs.trusted_lists_only) {
        $trusted_lists_only = ConvertTo-Boolean $kwargs.trusted_lists_only
    }
    if ($kwargs.contacts_trusted) {
        $contacts_trusted = ConvertTo-Boolean $kwargs.contacts_trusted
    }
    if ($kwargs.enabled) {
        $enabled = ConvertTo-Boolean $kwargs.enabled
    }

    # Execute commands - No output for the command
    $client.SetJunkRules($kwargs.mailbox, $add_blocked_senders_and_domains, $remove_blocked_senders_and_domains,
        $add_trusted_senders_and_domains, $remove_trusted_senders_and_domains,
        $trusted_lists_only, $contacts_trusted, $enabled)

    $raw_response = @{}
    $human_readable = "$script:INTEGRATION_NAME - '$($kwargs.mailbox)' Junk rules **modified**!"
    $entry_context = @{}

    return $human_readable, $entry_context, $raw_response
}

function  CreateAddAndRemoveSections([string[]]$items_to_add, [string[]]$items_to_remove ){
    $params = @{}
    if (-not [string]::IsNullOrEmpty($items_to_add)){
        $params["Add"] = $items_to_add
    }
    if (-not [string]::IsNullOrEmpty($items_to_remove)){
        $params["Remove"] =  $items_to_remove
    }
    return $params
}

function SetGlobalJunkRulesCommand([ExchangeOnlinePowershellV3Client]$client, [hashtable]$kwargs) {
    # Parse arguments
    $add_blocked_senders_and_domains = ArgToList $kwargs.add_blocked_senders_and_domains
    $remove_blocked_senders_and_domains = ArgToList $kwargs.remove_blocked_senders_and_domains
    $add_trusted_senders_and_domains = ArgToList $kwargs.add_trusted_senders_and_domains
    $remove_trusted_senders_and_domains = ArgToList $kwargs.remove_trusted_senders_and_domains
    if ($kwargs.trusted_lists_only) {
        $trusted_lists_only = ConvertTo-Boolean $kwargs.trusted_lists_only
    }
    if ($kwargs.contacts_trusted) {
        $contacts_trusted = ConvertTo-Boolean $kwargs.contacts_trusted
    }
    if ($kwargs.enabled) {
        $enabled = ConvertTo-Boolean $kwargs.enabled
    }
    # Execute commands - No output for the command
    $client.SetGlobalJunkRules($kwargs.mailbox, $add_blocked_senders_and_domains, $remove_blocked_senders_and_domains,
        $add_trusted_senders_and_domains, $remove_trusted_senders_and_domains,
        $trusted_lists_only, $contacts_trusted, $enabled)

    $raw_response = @{}
    $human_readable = "$script:INTEGRATION_NAME - Junk rules globally **modified**!"
    $entry_context = @{}

    return $human_readable, $entry_context, $raw_response
}

function GetMessageTraceCommand([ExchangeOnlinePowershellV3Client]$client, [hashtable]$kwargs) {
    # Parse arguments
    $sender_address = ArgToList $kwargs.sender_address
    $recipient_address = ArgToList $kwargs.recipient_address

    $raw_response = $client.GetMessageTrace($sender_address, $recipient_address, $kwargs.from_ip, $kwargs.to_ip, $kwargs.message_id,
        $kwargs.message_trace_id, $kwargs.page, $kwargs.page_size, $kwargs.start_date,
        $kwargs.end_date, $kwargs.status)

    $entry_context = ParseMessageTraceToEntryContext $raw_response
    if ($entry_context.($script:MESSAGE_TRACE_ENTRY_CONTEXT)) {
        $human_readable = TableToMarkdown $entry_context.($script:MESSAGE_TRACE_ENTRY_CONTEXT)  "$script:INTEGRATION_NAME - Messages trace"
    }
    else {
        $human_readable = "**No messages trace found**"
    }

    return $human_readable, $entry_context, $raw_response
}

function GetMessageTraceListCommand([ExchangeOnlinePowershellV3Client]$client, [hashtable]$kwargs) {
    # Parse arguments
    $sender_address = ArgToList $kwargs.sender_address
    $recipient_address = ArgToList $kwargs.recipient_address
    $message_id = ArgToList $kwargs.message_id
    $status = ArgToList $kwargs.status

    $raw_response = $client.GetMessageTraceList($sender_address, $recipient_address, $kwargs.from_ip, $kwargs.to_ip, $message_id,
        $kwargs.message_trace_id, $kwargs.start_date, $kwargs.end_date, $status, $kwargs.subject, $kwargs.subject_filter_type,
        $kwargs.starting_recipient_address, $kwargs.limit)

    $entry_context = ParseMessageTraceToEntryContext $raw_response
    if ($entry_context.($script:MESSAGE_TRACE_ENTRY_CONTEXT)) {
        $human_readable = TableToMarkdown $entry_context.($script:MESSAGE_TRACE_ENTRY_CONTEXT)  "$script:INTEGRATION_NAME - Messages trace"
    }
    else {
        $human_readable = "**No messages trace found**"
    }

    return $human_readable, $entry_context, $raw_response
}

function GetFederationTrustCommand([ExchangeOnlinePowershellV3Client]$client, [hashtable]$kwargs) {
    [CmdletBinding()]
    # parse arguments
    $domain_controller = $kwargs.domain_controller
    $identity = $kwargs.identity
    $raw_response = $client.GetFederationTrust(
        $domain_controller, $identity
    )
    $human_readable = TableToMarkdown $raw_response "Results of $command"
    $entry_context = @{
        "$script:INTEGRATION_ENTRY_CONTEXT.FederationTrust(obj.ApplicationIdentifier === val.ApplicationIdentifier)" = $raw_response
    }
    Write-Output $human_readable, $entry_context, $raw_response
}
function GetFederationConfigurationCommand {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    # parse arguments
    $domain_controller = $kwargs.domain_controller
    $identity = $kwargs.identity
    $include_extended_domain_info = ConvertTo-Boolean $kwargs.include_extended_domain_info
    $raw_response = $client.GetFederationConfiguration(
        $domain_controller,
        $identity,
        $include_extended_domain_info
    )
    $human_readable = TableToMarkdown $raw_response "Results of $command"
    $entry_context = @{
        "$script:INTEGRATION_ENTRY_CONTEXT.FederationConfiguration(obj.Guid === val.Guid)" = $raw_response
    }
    Write-Output $human_readable, $entry_context, $raw_response
}
function GetRemoteDomainCommand {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $identity = $kwargs.identity
    $domain_controller = $kwargs.domain_controller
    $raw_response = $client.GetRemoteDomain($domain_controller, $identity)
    $human_readable = TableToMarkdown $raw_response "Results of $command"
    $entry_context = @{"$script:INTEGRATION_ENTRY_CONTEXT.RemoteDomain(obj.Guid === val.Guid)" = $raw_response }
    Write-Output $human_readable, $entry_context, $raw_response
}
function GetUserCommand {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $identity = $kwargs.identity
    $organizational_unit = $kwargs.organizational_unit
    $limit = ($kwargs.limit -as [int])
    $raw_response = $client.GetUser($identity, $organizational_unit, $limit)
    $human_readable = TableToMarkdown $raw_response "Results of $command"
    $entry_context = @{"$script:INTEGRATION_ENTRY_CONTEXT.User(obj.Guid === val.Guid)" = $raw_response}
    Write-Output $human_readable, $entry_context, $raw_response
}
function GetMailboxAuditBypassAssociationCommand {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $identity = $kwargs.identity
    $domain_controller = $kwargs.domain_controller
    $limit = ($kwargs.limit -as [int])
    $raw_response = $client.GetMailboxAuditBypassAssociation($identity, $domain_controller, $limit)
    $human_readable = TableToMarkdown $raw_response "Results of $command"
    $entry_context = @{"$script:INTEGRATION_ENTRY_CONTEXT.MailboxAuditBypassAssociation(obj.Guid === val.Guid)" = $raw_response }
    Write-Output $human_readable, $entry_context, $raw_response
}
function ListRulesCommand {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $mailbox = $kwargs.mailbox
    $limit = ($kwargs.limit -as [int])
    $raw_response = $client.GetRules($mailbox, $limit)
    if($raw_response -eq $null){
        Write-Output "No Rules were found."
    }
    else{
        $parsed_raw_response = ParseRawResponse $raw_response
        $md_columns = $raw_response | Select-Object -Property Identity, Name, Enabled, Priority, RuleIdentity
        $human_readable = TableToMarkdown $md_columns "Results of $command"
        $entry_context = @{"$script:INTEGRATION_ENTRY_CONTEXT.Rule(obj.RuleIdentity === val.RuleIdentity)" = $parsed_raw_response }
        Write-Output $human_readable, $entry_context, $parsed_raw_response
    }
}
function GetRuleCommand {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $mailbox = $kwargs.mailbox
    $identity = $kwargs.identity
    $raw_response = $client.GetRule($mailbox, $identity)
    if($raw_response -eq $null){
        Write-Output "No Rule with identity $identity was found."
    }
    else{
        $parsed_raw_response = ParseRawResponse $raw_response

        $md_columns = $raw_response | Select-Object -Property RuleIdentity, Name, Enabled, Priority, Description, StopProcessingRules, IsValid
        $human_readable = TableToMarkdown $md_columns "Results of $command"
        $entry_context = @{"$script:INTEGRATION_ENTRY_CONTEXT.Rule(obj.RuleIdentity == val.RuleIdentity)" = $parsed_raw_response }
        Write-Output $human_readable, $entry_context, $parsed_raw_response
    }

}
function RemoveRuleCommand {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $mailbox = $kwargs.mailbox
    $identity = $kwargs.identity
    $result = $client.RemoveRule($mailbox, $identity)
    $raw_response = @{}
    $human_readable = "Rule $identity has been deleted successfully"
    $entry_context = @{}
    Write-Output $human_readable, $entry_context, $raw_response
}
function DisableRuleCommand {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $mailbox = $kwargs.mailbox
    $identity = $kwargs.identity
    $raw_response = $client.DisableRule($mailbox, $identity)
    $human_readable = "Rule $identity has been disabled successfully"
    $entry_context = @{}
    Write-Output $human_readable, $entry_context, $raw_response
}
function EnableRuleCommand {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $mailbox = $kwargs.mailbox
    $identity = $kwargs.identity
    $raw_response = $client.EnableRule($mailbox, $identity)
    $human_readable = "Rule $identity has been enabled successfully"
    $entry_context = @{}
    Write-Output $human_readable, $entry_context, $raw_response
}
function GetMailFlowRuleParamsFromEntryId([string]$entry_id) {
    $file_path = ($demisto.GetFilePath($entry_id)).path
    if (-not $file_path) {
        throw "Could not resolve the file path for entry ID '$entry_id'."
    }
    $file_content = Get-Content -Path $file_path -Raw
    $params_from_file = @{}
    ($file_content | ConvertFrom-Json).PSObject.Properties | ForEach-Object {
        $params_from_file[$_.Name] = $_.Value
    }
    return $params_from_file
    <#
        .DESCRIPTION
        Reads a JSON file (referenced by a War Room entry ID) and returns its parameters as a hashtable.
        The JSON is expected to be a map of PowerShell parameter names to values.

        .PARAMETER entry_id
        The War Room entry ID of the JSON file.

        .OUTPUTS
        Hashtable - The parameters parsed from the file.
    #>
}

function BuildMailFlowRuleParams([hashtable]$kwargs) {
    # Maps the content (snake_case) arguments to the PowerShell (PascalCase) parameter names.
    # Only arguments that were actually provided are added, with the correct type cast.
    $cmd_params = @{}

    # String conditions / metadata (passed as-is).
    $string_args = @{
        "name"                             = "Name"
        "identity"                         = "Identity"
        "mode"                             = "Mode"
        "subject_contains_words"           = "SubjectContainsWords"
        "except_if_subject_contains_words" = "ExceptIfSubjectContainsWords"
        "reject_message_reason_text"       = "RejectMessageReasonText"
        "comments"                         = "Comments"
    }
    foreach ($arg in $string_args.Keys) {
        if (-not [string]::IsNullOrEmpty($kwargs.$arg)) {
            $cmd_params[$string_args.$arg] = $kwargs.$arg
        }
    }

    # Integer arguments.
    if (-not [string]::IsNullOrEmpty($kwargs.priority)) {
        $cmd_params["Priority"] = $kwargs.priority -as [int]
    }

    # Array arguments.
    $array_args = @{
        "from"    = "From"
        "sent_to" = "SentTo"
    }
    foreach ($arg in $array_args.Keys) {
        if (-not [string]::IsNullOrEmpty($kwargs.$arg)) {
            $cmd_params[$array_args.$arg] = ArgToList $kwargs.$arg
        }
    }

    # Boolean action arguments.
    $bool_args = @{
        "quarantine"     = "Quarantine"
        "delete_message" = "DeleteMessage"
    }
    foreach ($arg in $bool_args.Keys) {
        if (-not [string]::IsNullOrEmpty($kwargs.$arg)) {
            $cmd_params[$bool_args.$arg] = ConvertTo-Boolean $kwargs.$arg
        }
    }

    return $cmd_params
    <#
        .DESCRIPTION
        Builds the hashtable of parameters (mapped to the New-/Set-TransportRule parameter names)
        from the raw command arguments. Only provided arguments are included, cast to the proper type.

        .PARAMETER kwargs
        The raw command arguments.

        .OUTPUTS
        Hashtable - Parameters ready to be splatted to New-TransportRule / Set-TransportRule.
    #>
}

function MergeEntryIdParams([hashtable]$cmd_params, [hashtable]$params_from_file) {
    # Merges parameters read from the entry_id file into cmd_params.
    # The entry_id file takes precedence: its values override values set from command arguments.
    foreach ($key in $params_from_file.Keys) {
        $cmd_params[$key] = $params_from_file[$key]
    }
    return $cmd_params
    <#
        .DESCRIPTION
        Merges file-provided parameters into cmd_params. The entry_id file is authoritative:
        any parameter present in the file overrides the corresponding value from the command arguments.

        .PARAMETER cmd_params
        The parameters built from explicit command arguments.

        .PARAMETER params_from_file
        The parameters parsed from the entry_id JSON file.

        .OUTPUTS
        Hashtable - The merged parameters.
    #>
}

function NewMailFlowRuleCommand {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]$client,
        [hashtable]$kwargs
    )
    $has_entry_id = -not [string]::IsNullOrEmpty($kwargs.entry_id)

    # Build the final parameter set first (command args + entry_id file), then validate the
    # RESULT. New-TransportRule's -Name is a mandatory parameter, so if the merged params
    # lack a Name the cmdlet would block on an interactive prompt (which hangs the container).
    # Validating the merged params guards this whether the name comes from an argument, the
    # file, or neither.
    $cmd_params = BuildMailFlowRuleParams $kwargs
    if ($has_entry_id) {
        $params_from_file = GetMailFlowRuleParamsFromEntryId $kwargs.entry_id
        $cmd_params = MergeEntryIdParams $cmd_params $params_from_file
    }

    if ([string]::IsNullOrEmpty($cmd_params.Name)) {
        throw "A rule name is required. Provide the 'name' argument or include 'Name' in the entry_id file."
    }

    # A transport rule must have at least one action; otherwise Exchange rejects it. When an
    # entry_id file is provided we let Exchange validate (the file may carry other action
    # parameters beyond the three exposed here), otherwise we check the built-in actions.
    if (-not $has_entry_id) {
        $action_args = @("reject_message_reason_text", "quarantine", "delete_message")
        $has_action = $false
        foreach ($action in $action_args) {
            if (-not [string]::IsNullOrEmpty($kwargs.$action)) {
                $has_action = $true
                break
            }
        }
        if (-not $has_action) {
            throw "At least one action must be provided. Please specify one of: reject_message_reason_text, quarantine, or delete_message."
        }
    }

    $extended_output = ConvertTo-Boolean $kwargs.extended_output
    $raw_response = $client.CreateMailFlowRule($cmd_params)
    $parsed_raw_response = ParseRawResponse $raw_response
    $entry_context = MailFlowRuleEntryContext $parsed_raw_response $extended_output
    $md_columns = $raw_response | Select-Object -Property Identity, Name, State, Mode, Priority, IsRuleConfigurationSupported, Comments
    $human_readable = TableToMarkdown $md_columns "Mail flow rule '$($cmd_params.Name)' was created successfully"
    Write-Output $human_readable, $entry_context, $parsed_raw_response
}

function SetMailFlowRuleCommand {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]$client,
        [hashtable]$kwargs
    )
    $has_entry_id = -not [string]::IsNullOrEmpty($kwargs.entry_id)

    # Build the final parameter set first (command args + entry_id file), then validate the
    # RESULT. Set-TransportRule's -Identity is a mandatory parameter, so if the merged params
    # lack an Identity the cmdlet would block on an interactive prompt (which hangs the
    # container). Validating the merged params guards this whether the identity comes from an
    # argument, the file, or neither.
    $cmd_params = BuildMailFlowRuleParams $kwargs
    if ($has_entry_id) {
        $params_from_file = GetMailFlowRuleParamsFromEntryId $kwargs.entry_id
        $cmd_params = MergeEntryIdParams $cmd_params $params_from_file
    }

    if ([string]::IsNullOrEmpty($cmd_params.Identity)) {
        throw "A rule identity is required. Provide the 'identity' argument or include 'Identity' in the entry_id file."
    }

    $raw_response = $client.UpdateMailFlowRule($cmd_params)
    $identity = $cmd_params.Identity
    $human_readable = "Mail flow rule $identity has been updated successfully"
    $entry_context = @{}
    Write-Output $human_readable, $entry_context, $raw_response
}

function ListMailFlowRulesCommand {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $extended_output = $kwargs.extended_output
    $limit = $kwargs.limit -as [int]
    $raw_response = $client.ListMailFlowRules($limit)
    if ($raw_response -eq $null) {
        Write-Output "No Mail Flow Rules were found."
    }
    else {
        $response = MailFlowRuleHelperFunction $raw_response $extended_output
        Write-Output $response
    }
}
function GetMailFlowRuleCommand {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $identity = $kwargs.identity
    $extended_output = $kwargs.extended_output
    $raw_response = $client.GetMailFlowRule($identity)
    if($raw_response -eq $null){
        Write-Output "No Mail Flow Rule were found."
    }
    else{
        $response = MailFlowRuleHelperFunction $raw_response $extended_output
        Write-Output $response
    }
}
function RemoveMailFlowRuleCommand {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $identity = $kwargs.identity
    $raw_response = $client.RemoveMailFlowRule($identity)
    $human_readable = "Mail flow rule $identity has been removed successfully"
    $entry_context = @{}
    Write-Output $human_readable, $entry_context, $raw_response
}
function DisableMailFlowRuleCommand {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $identity = $kwargs.identity
    $raw_response = $client.DisableMailFlowRule($identity)
    $human_readable = "Mail flow rule $identity has been disabled successfully"
    $entry_context = @{}
    Write-Output $human_readable, $entry_context, $raw_response
}
function EnableMailFlowRuleCommand {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $identity = $kwargs.identity
    $raw_response = $client.EnableMailFlowRule($identity)
    $human_readable = "Mail flow rule $identity has been enabled successfully"
    $entry_context = @{}
    Write-Output $human_readable, $entry_context, $raw_response
}
function DisableMailForwardingCommand {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ExchangeOnlinePowershellV3Client]$client,
        [hashtable]$kwargs
    )
    $identity = $kwargs.identity
    $raw_response = $client.DisableMailForwarding($identity)
    $human_readable = "Mail forwarding for user $identity has been disabled successfully"
    $entry_context = @{}
    Write-Output $human_readable, $entry_context, $raw_response
}
function TestModuleCommand($client)
{
    try
    {
        $client.CreateSession()
        $demisto.results("ok")
    }
    finally
    {
        $client.DisconnectSession()
    }

}
function Main
{
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")]
    param()
    $command = $demisto.GetCommand()
    $command_arguments = $demisto.Args()
    $integration_params = [Hashtable] $demisto.Params()
    if ($integration_params.password.password)
    {
        $password = ConvertTo-SecureString $integration_params.password.password -AsPlainText -Force
    }
    else
    {
        $password = $null
    }

    $exo_client = [ExchangeOnlinePowershellV3Client]::new(
            $integration_params.url,
            $integration_params.app_id,
            $integration_params.organization,
            $integration_params.certificate.password,
            $password
    )
    try
    {
        # Executing command
        $Demisto.Debug("Command being called is $Command")
        switch ($command)
        {
            "test-module" {
                ($human_readable, $entry_context, $raw_response) = TestModuleCommand $exo_client
            }
            "$script:COMMAND_PREFIX-cas-mailbox-list" {
                ($human_readable, $entry_context, $raw_response) = GetEXOCASMailboxCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-mailbox-list" {
                ($human_readable, $entry_context, $raw_response) = GetEXOMailBoxCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-mailbox-permission-list" {
                ($human_readable, $entry_context, $raw_response) = GetEXOMailBoxPermissionCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-recipient-permission-list" {
                ($human_readable, $entry_context, $raw_response) = GetEXORecipientPermissionCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-recipient-list" {
                ($human_readable, $entry_context, $raw_response) = GetEXORecipientCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-new-tenant-allow-block-list-items" {
                ($human_readable, $entry_context, $raw_response) = EXONewTenantAllowBlockListCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-email-security-block-sender-office-365-quick-action" {
                ($human_readable, $entry_context, $raw_response) = EXONewTenantAllowBlockListCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-get-tenant-allow-block-list-items" {
                ($human_readable, $entry_context, $raw_response) = EXOGetTenantAllowBlockListCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-get-tenant-allow-block-list-count" {
                ($human_readable, $entry_context, $raw_response) = EXOCountTenantAllowBlockListCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-remove-tenant-allow-block-list-items" {
                ($human_readable, $entry_context, $raw_response) = EXORemoveTenantAllowBlockListCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-email-security-unblock-sender-office-365-quick-action" {
                ($human_readable, $entry_context, $raw_response) = EXORemoveTenantAllowBlockListCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-export-quarantinemessage" {
                ($human_readable, $entry_context, $raw_response) = EXOExportQuarantineMessageCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-get-quarantinemessage" {
                ($human_readable, $entry_context, $raw_response) = EXOGetQuarantineMessageCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-release-quarantinemessage" {
                ($human_readable, $entry_context, $raw_response) = EXOReleaseQuarantineMessageCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-junk-rules-get" {
                ($human_readable, $entry_context, $raw_response) = GetJunkRulesCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-junk-rules-set" {
                ($human_readable, $entry_context, $raw_response) = SetJunkRulesCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-global-junk-rules-set" {
                ($human_readable, $entry_context, $raw_response) = SetGlobalJunkRulesCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-message-trace-get" {
                ($human_readable, $entry_context, $raw_response) = GetMessageTraceCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-message-trace-list" {
                ($human_readable, $entry_context, $raw_response) = GetMessageTraceListCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-federation-trust-get" {
                ($human_readable, $entry_context, $raw_response) = GetFederationTrustCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-federation-configuration-get" {
                ($human_readable, $entry_context, $raw_response) = GetFederationConfigurationCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-remote-domain-get" {
                ($human_readable, $entry_context, $raw_response) = GetRemoteDomainCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-user-list" {
                ($human_readable, $entry_context, $raw_response) = GetUserCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-mailbox-audit-bypass-association-list" {
                ($human_readable, $entry_context, $raw_response) = GetMailboxAuditBypassAssociationCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-rule-list" {
                ($human_readable, $entry_context, $raw_response) = ListRulesCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-get-rule" {
                ($human_readable, $entry_context, $raw_response) = GetRuleCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-remove-rule" {
                ($human_readable, $entry_context, $raw_response) = RemoveRuleCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-rule-disable" {
                ($human_readable, $entry_context, $raw_response) = DisableRuleCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-rule-enable" {
                ($human_readable, $entry_context, $raw_response) = EnableRuleCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-mail-flow-rules-list" {
                ($human_readable, $entry_context, $raw_response) = ListMailFlowRulesCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-mail-flow-rule-create" {
                ($human_readable, $entry_context, $raw_response) = NewMailFlowRuleCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-mail-flow-rule-update" {
                ($human_readable, $entry_context, $raw_response) = SetMailFlowRuleCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-mail-flow-rule-get" {
                ($human_readable, $entry_context, $raw_response) = GetMailFlowRuleCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-mail-flow-rule-remove" {
                ($human_readable, $entry_context, $raw_response) = RemoveMailFlowRuleCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-mail-flow-rule-disable" {
                ($human_readable, $entry_context, $raw_response) = DisableMailFlowRuleCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-mail-flow-rule-enable" {
                ($human_readable, $entry_context, $raw_response) = EnableMailFlowRuleCommand $exo_client $command_arguments
            }
            "$script:COMMAND_PREFIX-mail-forwarding-disable" {
                ($human_readable, $entry_context, $raw_response) = DisableMailForwardingCommand $exo_client $command_arguments
            }
            default {
                ReturnError "Could not recognize $command" | Out-Null
            }
        }
        # Return results to Demisto Server
        ReturnOutputs $human_readable $entry_context $raw_response | Out-Null
    }
    catch
    {
        $Demisto.debug(
                "Integration: $script:INTEGRATION_NAME
        Command: $command
        Arguments: $( $command_arguments | ConvertTo-Json )
        Error: $( $_.Exception.Message )"
        )
        if ($command -ne "test-module")
        {
            ReturnError "Error:
            Integration: $script:INTEGRATION_NAME
            Command: $command
            Arguments: $( $command_arguments | ConvertTo-Json )
            Error: $( $_.Exception )" | Out-Null
        }
        else
        {
            ReturnError $_.Exception.Message | Out-Null
        }
    }
    finally
    {
        # Always disconnect the session, even if no sessions available.
        $exo_client.DisconnectSession()
    }
}

# Execute Main when not in Tests
if ($MyInvocation.ScriptName -notlike "*.tests.ps1" -AND -NOT$Test)
{
    Main
}