Using New-TransportRule in Powershell: All You Need To Know

Mail flow rules, also known as Transport Rules, are essential for managing and controlling email traffic across an organization using Exchange or Exchange Online. They provide administrators the ability to define specific conditions and actions for handling email messages - automating tasks like message encryption, blocking emails, modifying headers, or generating Non-Delivery Reports (NDRs).
The new-TransportRule PowerShell cmdlet is the entry point for creating these rules programmatically, giving administrators granular control over mail behavior without relying solely on the Exchange Admin Center.
What is the new-TransportRule Cmdlet?
The new-TransportRule cmdlet is used in PowerShell to create mail flow rules in an Exchange Server or Exchange Online environment. These rules inspect messages in transit and apply actions based on defined conditions and exceptions. Whether you're managing message classification, applying DLP policies, controlling S/MIME encrypted messages, or using keywords in the subject line, this cmdlet allows precise configuration and rule enforcement.
It's available across versions of Exchange Server (2010, 2013, 2016, 2019) and in Exchange Online, supporting environments that use Microsoft 365, Exchange Online Protection, or on-premises MailBox servers.
Mail flow rules are commonly used to:
- Enforce compliance (e.g., block messages with sensitive information types)
- Apply message encryption via Microsoft Purview Message Encryption
- Add disclaimers or modify message headers
- Redirect messages based on Recipient Email Addresses, Distribution Groups, or IP address ranges
Syntax
There are many parameters for new-TransportRule, but the core syntax follows this pattern:
new-TransportRule -Name "<RuleName>" [conditions] [actions] [exceptions] [other settings]
This cmdlet uses a parameter set, and depending on your rule complexity, you may include dozens of parameters. The name must be unique and is required. Every other parameter is optional depending on the scenario.
Parameters
Below are key parameters you can use with new-TransportRule, grouped by type:
General
- -Name – Unique name of the rule. Required.
- -Comments – Optional descriptive notes about the rule.
- -Enabled – Enables or disables the rule (default is true).
- -Priority – Defines rule evaluation order; lower numbers run first.
- -Mode – Specifies rule mode: Enforce, Audit, or TestWithoutNotify.
- -SetAuditSeverity – Defines audit severity level for reporting.
Conditions
- -From – Sender email address or addresses to match.
- -FromScope – Scope of sender (e.g., InOrganization, NotInOrganization).
- -SentTo – Recipient email addresses or distribution groups.
- -SentToScope – Scope of recipients (InOrganization, NotInOrganization, etc.).
- -SentToMemberOf – Messages sent to members of a specific group.
- -RecipientDomainIs – Matches messages sent to specific recipient domains.
- -SenderIpRanges – Filters messages sent from specified IP address ranges.
- -SubjectContainsWords – Detects specified words in the message subject. (On-premises only)
- -SubjectMatchesPatterns – Regex pattern matching on subject (On-premises only).
- -HeaderContainsMessageHeader – Looks for specific header presence (On-premises only).
- -HeaderMatchesMessageHeader – Matches header content via regex (On-premises only).
- -AttachmentHasExecutableContent – Detects executable file attachments.
- -AttachmentExtensionMatchesWords – Matches specified file extensions in attachments.
- -AttachmentIsPasswordProtected – Flags password-protected attachments.
- -ContentContainsWords – Matches specific words in message body or subject.
- -MessageContainsDataClassifications – Detects sensitive information types (DLP).
- -WithImportance – Filters messages by importance level (Low, Normal, High).
- -SenderDepartmentMatches – Matches Active Directory sender department attribute.
Actions
- -RejectMessageReasonText – Custom rejection text shown to sender.
- -DeleteMessage – Deletes the message silently without notifying sender or recipient.
- -SetSCL – Assigns spam confidence level (0-9) for spam filtering.
- -ApplyRightsProtectionTemplate – Applies Azure RMS encryption template.
- -GenerateIncidentReport – Sends incident report to specified mailbox.
- -ModerateMessageByUser – Routes message for moderator approval.
- -RedirectMessageTo – Redirects message to a specified recipient.
- -AddToRecipients – Adds recipients to the To line without removing original recipients.
- -PrependSubject – Adds text to the start of the subject line.
- -ApplyHtmlDisclaimerLocation – Where to apply disclaimer (Prepend, Append, or Wrap). (On-premises only)
- -ApplyHtmlDisclaimerText – Text of the disclaimer to add. (On-premises only)
- -ApplyHtmlDisclaimerFallbackAction – Defines fallback behavior if disclaimer fails. (On-premises only)
- -SetHeaderName and -SetHeaderValue – Adds or modifies message header fields.
Exceptions
- -ExceptIfFrom – Excludes messages from specified senders.
- -ExceptIfRecipientDomainIs – Excludes recipients in certain domains.
- -ExceptIfSentTo – Excludes messages sent to specified recipients or groups.
- -ExceptIfSubjectContainsWords – Excludes messages with specific words in subject.
- -ExceptIfFromScope – Excludes messages based on sender scope.
New-TransportRule vs Set-TransportRule
Practical Uses
The new-TransportRule cmdlet is versatile and can address many real-world scenarios where controlling mail flow is critical for security, compliance, and operational efficiency. Here are three practical situations where this cmdlet shines:
1. Enforcing Data Loss Prevention (DLP) and Compliance Policies
Organizations often need to prevent sensitive data from leaving their network, such as credit card numbers, social security numbers, or proprietary information.
Using new-TransportRule, you can create rules that scan message content and attachments for sensitive information types, automatically blocking or quarantining those emails.
This reduces the risk of accidental leaks and helps meet regulatory requirements such as HIPAA or GDPR. You can also trigger incident reports to compliance officers when such rules are violated.
2. Automating Message Encryption and Rights Protection
In companies where confidentiality is critical, messages containing certain keywords or sent to external partners may require encryption or application of Azure Rights Management templates.
With new-TransportRule, administrators can configure rules to automatically apply Microsoft Purview Message Encryption or add rights protection based on message content, recipients, or sender attributes. This automation ensures consistent application of security policies without user intervention.
3. Managing Spam, Phishing, and Unauthorized Attachments
Email is a prime vector for spam and phishing attacks. By leveraging conditions like sender IP ranges, attachment types, or specific message header patterns, new-TransportRule lets you create targeted rules to reject or flag suspicious emails.
For example, you can reject messages with executable attachments or those originating from blacklisted IPs. Assigning spam confidence levels (SCL) and generating alerts or incident reports improves the security posture and helps administrators quickly respond to threats.
Prerequisites
To successfully use the new-TransportRule cmdlet, you need to meet the following requirements, based strictly on the official Microsoft documentation and typical Exchange environments:
- Permissions: You must have the Exchange Administrator role or equivalent permissions assigned in Exchange Online or your on-premises Exchange environment. Specifically, you need to be a member of a role group that includes the Mail Flow management role, which allows creating and managing transport rules.
- Exchange Version: The cmdlet is supported in Exchange Server 2010, 2013, 2016, 2019, and Exchange Onlinewithin Microsoft 365 environments. Some parameters or features might only be available on specific versions or in Exchange Online.
- PowerShell Module: For Exchange Online, you must connect via the Exchange Online PowerShell module (EXO V2 module) or older remote PowerShell sessions that provide the Exchange cmdlets. Ensure you are running a supported PowerShell version and have authenticated to your tenant or on-premises Exchange.
- Mail Flow Infrastructure: The cmdlet interacts with the mail flow pipeline, so your organization must be configured to route mail through Exchange Transport Services (for on-premises) or Exchange Online Protection (for cloud mail flow).
- Naming Requirements: The -Name parameter for your transport rule must be unique within your organization’s mail flow rules.
- Policy Considerations: In hybrid environments, be aware of differences between on-premises and cloud transport rules, as not all parameters or conditions may be supported equally.
How to Use new-TransportRule
Here are some of the most practical and commonly used scenarios for creating mail flow rules with new-TransportRule, using valid parameter combinations according to Microsoft’s official guidance.
1. Block Emails from a Specific Sender
new-TransportRule -Name "BlockSpecificSender" -From "badguy@example.com" -RejectMessageReasonText "Emails from this sender are not allowed."
This rule blocks messages originating from a specific sender email address by rejecting the message outright with a custom rejection message.
The condition -From targets emails sent from the specified address.
Using -RejectMessageReasonText informs the sender why their message was rejected. This rule prevents unwanted or malicious senders from delivering mail to recipients, stopping potentially harmful or spam emails at the transport level before reaching user inboxes.
2. Apply Azure Rights Management Template for External Recipients
new-TransportRule -Name "EncryptExternalEmails" -SentToScope NotInOrganization -ApplyRightsProtectionTemplate "Confidential"
This rule applies a specified Azure Rights Management encryption template automatically to all messages sent to recipients outside the organization. The -SentToScope NotInOrganization condition limits the rule to external recipients only. The -ApplyRightsProtectionTemplate action enforces message encryption, protecting content confidentiality beyond your organizational boundary. This automates enforcement of data security policies, ensuring sensitive emails sent externally remain protected with rights management.
3. Prepend Warning Text to Email Subjects Containing Specific Words
new-TransportRule -Name "WarnSubjectContainsConfidential" -SubjectContainsWords "confidential", "internal use only" -PrependSubject "[Warning]"
This rule prepends a warning label to the subject of emails that contain specified sensitive words or phrases in the subject line.
The -SubjectContainsWords condition matches keywords such as "confidential" or "internal use only".
The -PrependSubject action adds a prefix to the subject line, alerting recipients about the sensitive nature of the message before opening it. This helps raise awareness and caution among email recipients regarding content sensitivity.
4. Redirect Emails with Executable Attachments to a Security Team
new-TransportRule -Name "RedirectExecutableAttachments" -AttachmentHasExecutableContent $true -RedirectMessageTo securityteam@meetingroom365.com
This rule identifies emails that contain executable files (e.g., .exe, .dll) attached, using the -AttachmentHasExecutableContent condition set to true.
Instead of delivering the message to the original recipient, the -RedirectMessageTo action forwards it to a designated security mailbox for inspection. This approach provides a layer of defense by routing potentially dangerous attachments to security personnel, reducing the risk of malware infection.
5. Generate Incident Report When Sensitive Information Types Are Detected
new-TransportRule -Name "ReportSensitiveData" -MessageContainsDataClassifications "Credit Card Number", "Social Security Number" -GenerateIncidentReport compliance@meetingroom365.com
This rule detects email messages containing classified sensitive information types like credit card numbers or social security numbers through -MessageContainsDataClassifications condition. When triggered, it sends a detailed incident report to a compliance officer’s mailbox specified by -GenerateIncidentReport.
This helps organizations comply with data protection regulations by monitoring and responding to potential leaks of personally identifiable or financial information.
6. Set Spam Confidence Level for Messages from Specific IP Ranges
new-TransportRule -Name "MarkSpamFromIPs" -SenderIpRanges 192.168.0.0/24, 10.0.0.0/8 -SetSCL 9
This rule targets emails originating from defined IP address ranges using -SenderIpRanges. It applies a spam confidence level (SCL) of 9 through the -SetSCL action, marking these messages as highly likely spam.
This enhances spam filtering by flagging or quarantining messages based on their source IP, which is useful when dealing with suspicious or known bad IP addresses.
7. Require Moderation for Emails Sent to a Distribution Group
new-TransportRule -Name "ModerateSensitiveGroup" -SentTo "sensitive-group@meetingroom365.com" -ModerateMessageByUser "moderator@example.com"
This rule enforces moderation on all emails sent to a specified distribution group. The -SentTo condition filters messages addressed to the group email. The -ModerateMessageByUser action forwards these messages to a designated moderator for approval before delivery.
This prevents unauthorized or inappropriate content from reaching group members and maintains tighter control over important mailing lists.
8. Reject Emails with Password-Protected Attachments
new-TransportRule -Name "BlockPasswordProtectedAttachments" -AttachmentIsPasswordProtected $true -RejectMessageReasonText "Password-protected attachments are not allowed."
This rule identifies emails containing password-protected files using the -AttachmentIsPasswordProtected condition. It rejects such messages outright and returns the specified rejection message to the sender.
This protects recipients from receiving encrypted or hidden files, which are often used to conceal malware or sensitive data.
9. Remove a Specific Message Header from Emails
new-TransportRule -Name "RemoveXInternalHeader" -HeaderContainsMessageHeader "X-Internal-Info" -RemoveHeader "X-Internal-Info"
This rule targets emails that contain a specific message header ("X-Internal-Info") using -HeaderContainsMessageHeader and removes that header from the message before delivery using -RemoveHeader.
With this rule, you can prevent potentially sensitive or internal metadata from being exposed to recipients, which could otherwise reveal internal routing or configuration details.
10. Redirect Messages Sent to a Dynamic Distribution Group to a Compliance Mailbox
new-TransportRule -Name "RedirectDynamicGroup" -SentToMemberOf "DynamicGroupName" -RedirectMessageTo compliance@meetingroom365.com
This rule applies to emails sent to members of a dynamic distribution group via -SentToMemberOf condition. It redirects matching messages to a compliance mailbox for auditing or review purposes using -RedirectMessageTo.
This allows compliance teams to monitor communications targeted at groups that may frequently change membership or include sensitive audiences.
11. Delete Emails Containing Executable Attachments Silently
new-TransportRule -Name "DeleteExeAttachments" -AttachmentHasExecutableContent $true -DeleteMessage $true
This rule detects emails with executable file attachments using the -AttachmentHasExecutableContent condition and deletes them silently without sending Non-Delivery Reports or notifying the sender or recipients.
This approach is useful in highly secure environments where executable attachments are strictly forbidden, preventing any chance of delivery or alert noise.
12. Add a Custom Message Header to Emails from a Specific Department
new-TransportRule -Name "AddDeptHeader" -SenderDepartmentMatches "Finance" -SetHeaderName "X-Department" -SetHeaderValue "Finance"
This rule targets messages sent by users whose Active Directory department attribute matches "Finance". It adds or modifies the custom message header X-Department with the value "Finance" using -SetHeaderName and -SetHeaderValue. This can be used for downstream message processing, filtering, or archiving policies that rely on message header values.
Mail flow rules created with new-TransportRule empower administrators to enforce security, compliance, and operational policies consistently across Exchange environments.
Mastering these rules lets you automate complex mail handling scenarios, reduce risks like data leaks and malware, and improve visibility and control over message traffic.
Focus on testing rules thoroughly in audit or test modes before enforcing them to avoid unintended disruptions. With a solid grasp of key parameters and practical use cases, you can confidently shape your organization’s mail flow to meet evolving business and security demands.