Skip to content

Exchange PowerShell

Get Exchnage email message flow (delivery report)

Get-AgentLog -StartDate "09/25/2015 09:00:00" -EndDate "09/25/2015 18:00:00" -Location "C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\AgentLog" | where P1FromAddress -eq "example@mail.ru"  | Select-Object Timestamp,IPAddress,P1FromAddress,Recipients,Agent,Event,Action,SmtpResponse,Reason,ReasonData,Diagnostics | ConvertTo-Html > "C:\Users\user\Desktop\example_agent.html"
Get-MessageTrackingLog -Start "09/25/2015 09:00:00" -Sender "example@mail.ru" | Select-Object Timestamp,ClientIp,ServerIp,Source,EventId,@{Name='Recipients';Expression={[string]::join(“;”, ($_.Recipients))}},Sender,OriginalClientIp,MessageInfo | ConvertTo-Html > "C:\Users\user\Desktop\example_track.html"
Search-MessageTrackingReport -Identity "Name Surname" -Sender "example@mail.ru" -BypassDelegateChecking -DoNotResolve -TraceLevel High | ForEach-Object { Get-MessageTrackingReport -Identity $_.MessageTrackingReportID -DetailLevel Verbose -BypassDelegateChecking -DoNotResolve -RecipientPathFilter "Name.Surname@company.com" -ReportTemplate RecipientPath -TraceLevel High} | Select-Object –ExpandProperty RecipientTrackingEvents | Sort-Object Date | Select-Object Date, RecipientAddress, Status, EventType, EventDescription, @{Name='EventData';Expression={[string]::join(“;”, ($_.EventData))}} | ConvertTo-Html > "C:\Users\user\Desktop\Get-MessageTrackingReport.html"

Get user mailbox blacklist junk filter

Get-MailboxJunkEmailConfiguration "Name Surname" -DomainController dc.company.com | select -ExpandProperty BlockedSendersAndDomains

Delete user blocked senders

Set-MailboxJunkEmailConfiguration "Name Surname" -BlockedSendersAndDomains @{remove="user@domain.eu"} -DomainController dc.company.com
Update-Safelist "Name Surname" -DomainController dc.company.com

Create Exchange/SfB meeting room

New-Mailbox –Name "Meeting Room 1" –Alias "meetingroom1" –UserPrincipalName "meetingroom1@company.com" –sAMAccountName "meetingroom1" –Room -RoomMailboxPassword (ConvertTo-SecureString -String “P@ssword” -AsPlainText -Force) -OrganizationalUnit  "OU=Rooms-KVS,OU=company,DC=company,DC=com" -EnableRoomMailboxAccount $true -Domaincontroller dc.company.com
Set-CalendarProcessing -Identity "meetingroom1" -AutomateProcessing AutoAccept -AddOrganizerToSubject $true -DeleteComments $false -DeleteSubject $false -BookingWindowInDays 360 -Domaincontroller dc.company.com
Set-MailboxFolderPermission -Identity "meetingroom1:\calendar" -User default -AccessRights LimitedDetails  -Domaincontroller dc.company.com
Enable-CsMeetingRoom -Identity "meetingroom1" -SipAddress "sip:meetingroom1@company.com"  -RegistrarPool "skypeforbusiness.company.com" -Domaincontroller dc.company.com
New-DistributionGroup -Name "SPB Meeting Rooms" –Alias "spbmeetingrooms" -OrganizationalUnit "OU=Rooms-KVS,OU=company,DC=company,DC=com" -RoomList
Add-DistributionGroupMember -Identity spbmeetingrooms -Member meetingroom1 
Get-DistributionGroup -Domaincontroller dc.company.com | Where {$_.RecipientTypeDetails -eq "RoomList"}
Get-Mailbox -Domaincontroller dc.company.com | Where-Object {$_.RecipientTypeDetails -eq "RoomMailbox"}
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon]
"DefaultDomainName"="KVK" - String Value (REG_SZ) 
"AutoAdminLogon"="1" - String Value (REG_SZ) 
"DefaultUserName"="meetingroom1" - String Value (REG_SZ) 
"DefaultPassword"="P@ssword" - String Value (REG_SZ) 
Settings > Accounts > Sign-in options. Here under Require sign-in Never

Set retention policy for resource mailbox

First we create two Retention Policy Tags(RPT): for Sent and for Deleted items.

New-RetentionPolicyTag “RPT-PermanentlyDelete-DeletedItems” -Type DeletedItems -RetentionEnabled $true -AgeLimitForRetention 1 -RetentionAction PermanentlyDelete
New-RetentionPolicyTag “RPT-PermanentlyDelete-SentItems” -Type SentItems -RetentionEnabled $true -AgeLimitForRetention 1 -RetentionAction PermanentlyDelete
New-RetentionPolicy “RP-MeetingRooms” -RetentionPolicyTagLinks “RPT-PermanentlyDelete-DeletedItems”,”RPT-PermanentlyDelete-SentItems”

Then we apply the policy to Resource Mailbox.

Set-Mailbox “meetingroom” –RetentionPolicy “RP-MeetingRooms”

After some time Managed Folder Assistant (MFA) runs and tags all messages in these folders.

Those expired got Permanently Deleted (you could change this in RetentionAction parameter).

Get receive connectors with anonymous rights

$objs=@(); Get-ReceiveConnector -DomainController dc.company.com | where {$_.PermissionGroups -match "AnonymousUsers" } | foreach { $ConnectorName = $_.Name;
$Bindings = $_.Bindings;
$Ports = @(); foreach ($Binding in $Bindings) { $Ports += $Binding.Port };
$FQDN = $_.FQDN;
$RemoteIPRanges = $_.RemoteIPRanges;
$IPACLs = @(); foreach ($RemoteIPRange in $RemoteIPRanges) { $IPACLs += $RemoteIPRange.Expression };
$Permissions = Get-ADPermission $_.Identity -User 'NT AUTHORITY\ANONYMOUS LOGON' | where {$_.AccessRights -match "ExtendedRight" } | select -ExpandProperty ExtendedRights
$UserRights = @(); foreach ($Permission in $Permissions) { $UserRights += $Permission };
$obj = [PSCustomObject]@{ConnectorName = $ConnectorName; Port = $([string]::join(", ", ($Ports))); FQDN = $FQDN; IPACL = $([string]::join(", ", ($IPACLs | sort))); UserRights = $([string]::join(", ", ($UserRights -match "SMTP" | sort )))};
$objs += $obj };
write-output $objs | Out-GridView

Set user photo

Import-Module ActiveDirectory
$photo = [byte[]](Get-Content C:\PS\admin_photo.jpg -Encoding byte)
Set-ADUser user -Replace @{thumbnailPhoto=$photo}
Import-RecipientDataProperty -Identity “use” -Picture -FileData ([Byte[]] $(Get-Content -Path “C:\PS\admin_photo.jpg” -Encoding Byte -ReadCount 0))
OR trhough Exchange Server Shell
$photo = ([Byte[]] $(Get-Content -Path "C:\Users\user.KVG\Downloads\user.jpg" -Encoding Byte -ReadCount 0))
Set-UserPhoto -Identity "name surname" -DomainController dc.company.com -PictureData $photo -Confirm:$False

Get users without photo thumbnail

Get-ADUser -Filter * -properties thumbnailPhoto | ? {(-not($_.thumbnailPhoto))} | select Name
Get-ADUser -SearchBase "OU=Users-KVS,OU=company,DC=company,DC=com" -Filter * -Properties * | ft SamAccountName, Name, mail
Get-ADUser -SearchBase "OU=Users-KVS,OU=company,DC=company,DC=com" -Filter * -Properties thumbnailPhoto | ? {(-not($_.thumbnailPhoto))} | sort Name | select Name,SamAccountName

Add X500 address to Exchange mailbox (exchange use to send mail internally)

(Get-Mailbox "Name Surname" -DomainController dc.company.com).EmailAddresses
Set-Mailbox -Identity "Name Surname" -Domaincontroller dc.company.com -EmailAddresses @{Add="x500:/o=company/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Recipients/cn=Name Surname"}

Exchange delete messages from mailbox

To use the DeleteContent switch you have to be assigned the Mailbox Import Export management role.

Assign Role to Admin group

New-ManagementRoleAssignment -Name "Import_Export_Organization_Management" -SecurityGroup "Organization Management" -Role "Mailbox Import Export"

Search emails without deletion

Search-Mailbox -Identity "IT Mailbox" -Domaincontroller dc.company.com -SearchQuery 'from:scom@company.com AND sent:2017/01/19..2018/06/19' -EstimateResultOnly

Search and delete emails

Search-Mailbox -Identity "IT Mailbox" -Domaincontroller dc.company.com -SearchQuery 'from:scom@company.com AND sent:2017/01/19..2018/06/19' -DeleteContent

Exchange set retention policy for resource room to delete

New-RetentionPolicyTag "RPT-PermanentlyDelete-DeletedItems" -Type DeletedItems -RetentionEnabled $true -AgeLimitForRetention 1 -RetentionAction PermanentlyDelete -Domaincontroller dc.company.com
New-RetentionPolicyTag "RPT-PermanentlyDelete-SentItems" -Type SentItems -RetentionEnabled $true -AgeLimitForRetention 1 -RetentionAction PermanentlyDelete -Domaincontroller dc.company.com
New-RetentionPolicy "RP-MeetingRooms" -RetentionPolicyTagLinks "RPT-PermanentlyDelete-DeletedItems","RPT-PermanentlyDelete-SentItems" -Domaincontroller dc.company.com
Set-Mailbox "meetingroomgarage" –RetentionPolicy "RP-MeetingRooms" -Domaincontroller dc.company.com

Get Exchange failed move request and bad items in them

$mrobjs=@(); Get-MoveRequest -resultsize unlimited | where {$_.status -match "Failed"} | foreach {$mrsobjs=@(); $report=Get-MoveRequestStatistics $_.DisplayName -IncludeReport;$DisplayName = $report.DisplayName;$report | select -ExpandProperty Report | select -ExpandProperty Baditems | ForEach {$Failure = $_.Failure; $BaditemsSubject = $_.Subject; $BaditemsKind = $_.Kind; $BaditemsClassifications = $_.ScoringClassifications; $BaditemsFolderName = $_.FolderName;$mrsobj = [PSCustomObject]@{DisplayName = $DisplayName; Failure = $Failure; BaditemsSubject = $BaditemsSubject; BaditemsKind = $BaditemsKind; BaditemsClassifications = $BaditemsClassifications; BaditemsFolderName = $BaditemsFolderName};$mrsobjs += $mrsobj};$mrobjs += $mrsobjs}; $mrobjs  | Sort-Object DisplayName | Out-GridView

Exchange get mailboxes total storage

Get-Mailbox -DomainController dc.company.com | Get-MailboxStatistics | ForEach-Object { $_.TotalItemSize.Value.ToMb() } | Measure-Object -sum

Grant user Send As right to mailbox

get-mailbox survey | Add-ADPermission -ExtendedRights Send-As -User KVK\USER

Grant user Full Access right to mailbox

get-mailbox survey | Add-MailboxPermission -User KVK\USER -AccessRights FullAccess -Inheritance Type All