Windows/exchange

Aus SchnallIchNet
Wechseln zu: Navigation, Suche

PowerShell

powershell commands


possible access rights

 The Access Rights parameters are as below:

    ReadItems:  The user has the right to read items within the specified folder.
    CreateItems   The user has the right to create items within the specified folder.
    EditOwnedItems   The user has the right to edit the items that the user owns in the specified folder.
    DeleteOwnedItems   The user has the right to delete items that the user owns in the specified folder.
    EditAllItems   The user has the right to edit all items in the specified folder.
    DeleteAllItems   The user has the right to delete all items in the specified folder.
    CreateSubfolders   The user has the right to create subfolders in the specified folder.
    FolderOwner   The user is the owner of the specified folder. The user has the right to view and move the folder and create subfolders. The user can’t read items, edit items, delete items, or create items.
    FolderContact   The user is the contact for the specified public folder.
    FolderVisible   The user can view the specified folder, but can’t read or edit items within the specified public folder.

The Roles with which we can provide the access rights are as below:

    None   FolderVisible
    Owner   CreateItems, ReadItems, CreateSubfolders, FolderOwner, FolderContact, FolderVisible, EditOwnedItems, EditAllItems, DeleteOwnedItems, DeleteAllItems
    PublishingEditor   CreateItems, ReadItems, CreateSubfolders, FolderVisible, EditOwnedItems, EditAllItems, DeleteOwnedItems, DeleteAllItems
    Editor   CreateItems, ReadItems, FolderVisible, EditOwnedItems, EditAllItems, DeleteOwnedItems, DeleteAllItems
    PublishingAuthor   CreateItems, ReadItems, CreateSubfolders, FolderVisible, EditOwnedItems, DeleteOwnedItems
    Author   CreateItems, ReadItems, FolderVisible, EditOwnedItems, DeleteOwnedItems
    NonEditingAuthor   CreateItems, ReadItems, FolderVisible
    Reviewer   ReadItems, FolderVisible
    Contributor   CreateItems, FolderVisible

Ref: http://technet.microsoft.com/en-us/library/dd298062(v=exchg.150).aspx

The following roles apply specifically to calendar folders:

    AvailabilityOnly   View only availability data
    LimitedDetails   View availability data with subject and location


create mailbox

Create a new mailbox

New-Mailbox -Name 'prospect NL' -Alias 'prospect.nl' -OrganizationalUnit 'arifleet.com/ARI Fleet Europe/Stuttgart/Rooms and Equipment' \
  -UserPrincipalName 'prospect.nl@arifleet.com' -SamAccountName 'prospect.nl' -FirstName 'prospect' -Initials  -LastName 'NL' \
  -Password 'System.Security.SecureString' -ResetPasswordOnNextLogon $false -Database 'Stuttgart Mailbox DB One'


create linked mailbox

New-Mailbox -Name 'Koroch, Ernst' -Alias 'ekoroch' -OrganizationalUnit 'arifleet.com/ARI Fleet Europe/Stuttgart/Users' -UserPrincipalName \
'ekoroch@arifleet.com' -SamAccountName 'ekoroch' -FirstName 'Ernst' -Initials  -LastName 'Koroch' -Database 'Stuttgart Mailbox DB One' \
-LinkedMasterAccount 'fleetservices\ekoroch' -LinkedDomainController 'dc03.fleetservices.intra' -LinkedCredential \
'System.Management.Automation.PSCredential'


Repair Mailbox

see: https://technet.microsoft.com/en-us/library/ff625221(v=exchg.141).aspx

New-MailboxRepairRequest -Mailbox <Emailaddress> -CorruptionType SearchFolder,AggregateCounts,ProvisionedFolder,FolderView [-DetectOnly]


Email-Enable AD Group

Enable-DistributionGroup <ADGroupID> -PrimarySmtpAddress yadda@domain.tld


Email-Enable AD User

Enable-Mailbox <UserID> -PrimarySmtpAddress yadda@domain.tld -displayname "Yadda, Yadda"


add mailbox permissions

Add full access to mailbox 'mailbox@arifleet.de' for user 'DOMAIN\user':

Add-MailboxPermission -Identity mailbox@arifleet.de -User DOMAIN\user -AccessRights Fullaccess -InheritanceType All

-AccessRights <right>
where <right> may be

FullAccess
ExternalAccount
DeleteItem
ReadPermission
ChangePermission
ChangeOwner

disable auto-mapping of

-Automapping $false


remove mailbox permissions

remove-MailboxPermission -Identity mailbox@arifleet.de -user domari\user -AccessRights Fullaccess -inheritance all


add/remove 'Send as' permissions

Add-ADPermission -Identity 'CN=Mahnwesen,OU=Users,OU=Stuttgart,OU=ARI Fleet Europe,DC=arifleet,DC=com' -User 'DOMARI\ntrgovcevic' -ExtendedRights 'Send-as'

You can grant the permissions by using Active Directory Users & Computers. Simply open the properties of the group, switch to the Security tab, add the mailbox user or group, and then tick the Send As box and apply the change. After making this change you may notice that it does not take effect for up to 2 hours. This is due to caching on the Exchange servers. Though you can speed up the change by restarting the Information Store that is obviously not going to be practical in most production environments, so you’ll often find that you just need to wait.

Remove-ADPermission -Identity 'CN=Mahnwesen,OU=Users,OU=Stuttgart,OU=ARI Fleet Europe,DC=arifleet,DC=com' -User 'DOMARI\ntrgovcevic' -ExtendedRights 'Send-as'


'Send as'/'SendOnBehalf' Distributiongroups

Set-DistributionGroup <DistributionGroupName> -GrantSendOnBehalfTo USER@arifleet.com

and sendOnBehalf for Distributiongroups


SentItem Configuration

Until Exchange 2010:

Set-MailboxSentItemsConfiguration <ALIAS> -SendAsItemsCopiedTo SenderAndFrom

Exchange 2016:

Set-Mailbox -identity <UPN> [-DomainController <HOSTNAME>] -MessageCopyForSentAsEnabled $true -MessageCopyForSendOnBehalfEnabled $true


add mailbox folder permissions

Add-MailboxFolderPermission -Identity poolcar@netcar24.com:\Calendar -user csteidl@arifleet.com -AccessRights <see RIGHTS>

Set default-rights for ressource mailboxes (to show up subjects a.s.o.):

Set-MailboxFolderPermission meetingroom:\Calendar -User Default -AccessRights Reviewer

get mailbox permissions

get permissions of fhess on mailbox prospect.be

Get-MailboxPermission -Identity prospect.be@arifleet.com -User "fhess"


get folder permissions

get-mailboxfolderpermission -identity fhess


get UPN of users

Get-MailboxFolderPermission "USER:\Kalender" | Foreach-Object { $_.User.ADRecipient.UserPrincipalName }


get full user details

Get-MailboxFolderPermission "USER:\Kalender" | Foreach-Object { $_.identity.adrecipient.identity }


Find permissions granted to spec. users

Get-Mailbox -RecipientType 'UserMailbox' -ResultSize Unlimited | Get-MailboxPermission | where { $_.user.tostring() -eq "DOMAIN\username" -and $_.IsInherited -eq $false }


enable autoreply / vacation message

set the message (optionally) and enable auto reply

$message = get-content message.txt
Set-MailboxAutoReplyConfiguration <alias> -AutoReplyState enabled \
                                          -ExternalAudience <none/all/known> \
                                          -InternalMessage "$message" \
                                          -ExternalMessage "$message"


disable auto-reply / vacation message

disable auto reply

Set-MailboxAutoReplyConfiguration <alias> -AutoReplyState disabled


Retention policies

create server side retention policies


Create Retention Policy Tag

New-RetentionPolicyTag "ARI STG - Delete all 180 days" -Type All -Comment "Deletes all items older 180 days" -RetentionEnabled $true \
-AgeLimitForRetention 180 -RetentionAction DeleteAndAllowRecovery

RetentionAction: MoveToFolder, MoveToDeletedItems, DeleteAndAllowRecovery, PermanentlyDelete, MoveToArchive


Create Retention Policy

New-RetentionPolicy "ARI STG - Delete ALL items older 180 days" -RetentionPolicyTagLinks "ARI STG - Delete all 180 days"

Activate policy by: Open Mailbox Properties --> Mailbox Settings --> Messaging Records Mgmt --> Apply Retention policy


get distribution group members

get-distributiongroupmember <group>
get-distributiongroupmember mailaddress@arifleet.de


get users by filter and add to distributiongroup

Get-ADUser -SearchBase 'OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=<DOMAIN>,DC=<DOMAIN>,DC=<TLD>' -filter \
{ (mail -like '*<PATTERN>*' -and (employeeType -ne 'MGR') -and enabled -eq 'true') } | \
%{ Add-DistributionGroupMember -identity '<GROUP>' -member $_.UserPrincipalName }
Get-ADUser -SearchBase 'OU=Stuttgart,OU=UserAccounts,OU=Accounts,DC=<DOMAIN>,DC=<DOMAIN>,DC=<TLD>' -filter \
{ (mail -like '*<PATTERN>*' -and (employeeType -eq 'MGR') -and enabled -eq 'true') } | \
%{ Add-DistributionGroupMember -identity '<GROUP>' -member $_.UserPrincipalName }


Get Mailbox by ExchangeGuid/Mapi-session

get-mailbox -ResultSize unlimited | where {$_.ExchangeGuid -eq "265182e3-a31c-4a9f-e38e-687f5a7c2d6b"}


Get Mailbox by Ressource type

Get-Mailbox -RecipientTypeDetails RoomMailbox
Get-Mailbox -RecipientTypeDetails EquipmentMailbox


Get Mail Public folder

Get-MailPublicFolder helpdesk@sub.domain.com | Get-PublicFolder [| Select *]


Logging

further logfiles can be found here:

C:\Program Files\Microsoft\Exchange Server\V14\TransportRoles\Logs\ProtocolLog


Track accross multiple servers

get-transportserver


e.g. that to "get-messagetrackinglog":

get-transportserver | get-messagetrackinglog


message tracking

get-messagetrackinglog -Sender 'user@arifleet.de' -Start "5/04/2015 5:00:00 AM" -End "5/15/2015 8:30:00 AM"
get-transportserver | get-messagetrackinglog -Sender 'system-mail.it@arifleet.de' \
get-transportservice | get-messagetrackinglog -Sender 'system-mail.it@arifleet.de' \
                                             -Start "6/01/2015 5:00:00 AM" \
                                             -End "6/01/2015 10:30:00 AM" \
                                             -resultsize unlimited | ft -Wrap
-MessageSubject <String>
-Recipients <String[]>
-Start/-End (get-date).AddHours(-1).toString()
-ResultSize Unlimited

some more examples:

get-messagetrackinglog -Recipients:recipient@email.be -Start "6/8/2015 4:42:00 AM" -End "6/9/2015 9:52:00 PM" | Select *,{$_.Recipients} | export-csv .\maillog.csv
Get-MessageTrackingLog -resultsize unlimited | \
where-object {$_.Recipients -like “*@gmail.com, *@yahoo.com” -AND $_.EventId -eq “Send”} |ft -auto >>C:\External mails.txt
Get-MessageTrackingLog -resultsize unlimited | sort -property Timestamp

repair mailbox

New-MailboxRepairRequest -Mailbox schaden@arifleet.de -CorruptionType SearchFolder


-CorruptionType ProvisionedFolder,SearchFolder,AggregateCounts,Folderview
-Archive        Prueft Mailbox _und_ Archive
-DetectOnly     Prueft nur, keine Reparatur!

Ergebnisse der Prüfung werden im Anwendungs Event-Log des Servers protokolliert. Die Events tragen die folgenden Ereignis-IDs:

10044,10045,10046,10047,10048,10049,10050,10051,10059,10062

mit einem rechtsklick auf 'Application' laesst dich das eventlog nach diesen ID's filtern.


move mailbox between exchange-databases

Move Mailboxes between exchange >= 2010 servers
the output is piped into 'ft' (format table) to get complete output and not stripped it...

New-MoveRequest -Identity mailbox@arifleet.de -TargetDatabase ‘Whatever Database-Name 001’ | ft -AutoSize -Wrap

create a batch

Get-Mailbox -Database "Stuttgart Mailbox DB One" | Where-Object { $_.alias -like "jira*" } | New-MoveRequest -TargetDatabase [...]

Options:

-BadItemLimit 0
-Suspend 
-SuspendComment "Resume after 11:00 p.m. PST"
-SuspendWhenReadyToComplete
-BatchName "Some Name to identify the Batch-Moves"

get moverequest status:

Get-MoveRequestStatistics "sadg"

Get-MoveRequest | Get-MoveRequestStatistics

Get-MoveRequest | Get-MoveRequestStatistics | select DisplayName,alias,Status,TotalMailboxSize,PercentComplete| ft


get Mailbox sizes

Get-MailboxDatabase | Where-Object { $_.Name -like "STG*" } | Get-MailboxStatistics | sort -property TotalItemSize -desc \
| select DisplayName,ItemCount,TotalItemSize,TotalDeletedItemSize |ft


get database size

Get-MailboxDatabase -status | select ServerName,Name,DatabaseSize

Get-MailboxDatabase -status | Sort-Object DatabaseSize -Desc | select ServerName,Name,DatabaseSize

Get-MailboxDatabase -status | Where-Object { $_.name -like "STG*" } | Sort -property DatabaseSize -Desc | select ServerName,Name,DatabaseSize

Export Mailbox (Folder)

New-MailboxExportRequest -mailbox schaden \
-includefolders "******@arifleet.de/00 UNFALLORDNER ab 1.3.2011/Storopack R+V (*.***@*******.com)  TK 150 \/ keine VK RA Schmid" \
-filepath "\\stgwpvinfEXC01\g$\Storopack R+V (*.***@*******.com)  TK 150_keine VK RA Schmid.pst"
  1. be sure to mask e.g. '/' characters in foldernames with '\'
  2. leave out -includefolders to export the entire mailbox
    1. add a '.../*' to -includefolders to include subfolders

Search Mailbox content

This one searches for all messages between 1/1/2017 and 12/31/2018 and creates copies of it within the Mailbox of targetmailbox into targetfolder:

Search-Mailbox -Identity <USER-ID> -SearchQuery "received>=01/01/2017 AND received<=12/31/2018" -targetmailbox "<TARGET-USER-ID>" -targetfolder "SearchResults"

SearchQuery examples:

"Subject:Project Hamilton"
"election OR candidate OR vote" - all messages that contain one of the words in whole message

If the Subject you are searching for contains COLONS, they need to be masked using back tick "Subject:AW`: yadda yadda"

Delete resulting emails:

 -deletecontent

set thumbnail-image

from an exchange server

Import-RecipientDataProperty -Identity dSchlenzig -Picture -FileData \
([Byte[]]$(Get-Content -path ".\thumb-DOMARI.jpg"  -Encoding Byte -ReadCount 0))


from an AD

$photo = [byte[]](Get-Content path of pic -Encoding byte)
Set-ADUser username -Replace @{thumbnailPhoto=$photo}


Import/Acivate new Certificate

Import-ExchangeCertificate -FriendlyName "webmail10102019" -PrivateKeyExportable $true -FileData ([Byte[]]$(Get-Content -Path c:\certificates\YOUR_CERTIFICATE.cer -Encoding byte -ReadCount 0))

In case of encrypted .pfx or something like that:

$pass = ConvertTo-SecureString "<PASSWORD>" -AsPlainText -Force
Import-ExchangeCertificate -FriendlyName "webmail10102019" -Password $pass -PrivateKeyExportable $true -FileData ([Byte[]]$(Get-Content -Path Webmail.pfx -Encoding byte -ReadCount 0))

activate:

Enable-ExchangeCertificate -Thumbprint 1234ae0567a72fccb75b1d0198628675333d010e -Services POP,IMAP,SMTP,IIS

DAG/Cluster stuff

Check who's master:

Get-ClusterGroup EU-DAG


Get detailed DAG info:

Get-DatabaseAvailabilityGroup STG-DAG -status | fl


Test replication health (do so on all cluster members):

Test-ReplicationHealth -server EXC02


Get mount status, copy/reply queue, Index state

Get-MailboxDatabaseCopyStatus -server exc01


Check Queues:

get-queue -server stgwpvinfexc02


Move queued messages to other server:

Redirect-Message -Server Mailbox01 -Target Mailbox02


Check service health (do so on all cluster members):
(test whether all the Microsoft Windows services that Exchange requires on a server have started)

Test-servicehealth –server EXC02


Test MapiConnectivity (Note: this will only test if the DB’s are mounted/active copy on the specific server):

Test-MapiConnectivity -server EXC02


Test/view replication:

Get-MailboxdatabaseCopystatus -server EXC02


Failover Cluster:

Get-ClusterNode EXC03 | Get-ClusterGroup | Move-ClusterGroup 

This will failover the 2 node cluster to the other node

Get-ClusterNode EXC03 | Get-ClusterGroup | Move-ClusterGroup -node EXC01

This will failover the cluster to the node EXC01


Move Databases:

Move-ActiveMailboxDatabase DB3 -ActivateOnServer MBX4

This example performs a switchover of the database DB3 to the Mailbox server MBX4. When the command completes, MBX4 hosts the active copy of DB3. Because the MountDialOverride parameter isn't specified, MBX4 mounts the database using a database auto mount dial setting of Lossless.


Get-MailboxDatabase stg-* | Move-ActiveMailboxDatabase -ActivateOnServer MBX4

Same as above, but moves all databases starting with 'STG-*' to MBX04


Move-ActiveMailboxDatabase DB1 -ActivateOnServer MBX3 -MountDialOverride:GoodAvailability

This example performs a switchover of the database DB1 to the Mailbox server MBX3. When the command completes, MBX3 hosts the active copy of DB1. Because the MountDialOverride parameter is specified with a value of Good Availability, MBX3 mounts the database using a database auto mount dial setting of GoodAvailability.

Outlook stuff

get all add-ins

Be aware that HKCU can only be grabbed if running in the user context!

$searchScopes = "HKCU:\SOFTWARE\Microsoft\Office\Outlook\Addins","HKLM:\SOFTWARE\Wow6432Node\Microsoft\Office\Outlook\Addins"
$searchScopes | % {Get-ChildItem -Path $_ | % {Get-ItemProperty -Path $_.PSPath} | Select-Object @{n="Name";e={Split-Path $_.PSPath -leaf}},FriendlyName,Description} | Sort-Object -Unique -Property name


Transport stuff

some stuff i used the GUI for


Relay Configuration (GUI)

Go:

Server-Configuration --> Hub Transport --> Receive Connectors (Tab)
- Select a valuable connector which matches you needs or create a new.
- for me there was 'Relay internal' which was to allow anonymous connects from spec. hosts/nets --> Double-Click
- Switch to 'Network'-Tab --> Add IP or rage to lower box.


Max connection from single IP

set-ReceiveConnector -Identity "exc03\Application_Relay" -MaxInboundConnectionPerSource 50

sets the max inbound connections per source IP to 50 (default 20)


Create an anonymous Receive Connector

after you created an receive connector by GUI you will have to run:

Get-ReceiveConnector "STGWPVINFEXC02\Application_Relay_Intern" | \
Add-ADPermission -User "NT AUTHORITY\ANONYMOUS LOGON" -ExtendedRights "Ms-Exch-SMTP-Accept-Any-Recipient"