PowerShell

Exchange

My Exchange Cheat Sheet

The following is a collection of common tasks that I save in the form of a script so that I can quickly modify highlight and f8 commands when I need them.


        "Don't run this as a script"
    
        Break;
        #region Creating a PST
        New-MailboxExportRequest -Mailbox Mailbox -FilePath '\\fileserver\psts\Mailbox.pst' 
        New-MailboxExportRequest -Mailbox Mailbox -FilePath '\\fileserver\psts\Mailbox.pst' -IsArchive
    
        #endregion
    
        #region Adding and Removing Distribution Group members
            Remove-DistributionGroupMember -Identity 'DistributionGroup' -Member memberToRemove
            Add-DistributionGroupMember -Identity 'DistributionGroup' -Member memberToAdd
    
        #endregion
    
        #region Add and Remove Permissions
        "Adding Calendar Permission"
        add-MailboxFolderPermission -Identity SharingUser":\calendar" -User ShareeUser -AccessRights owner
        Remove-MailboxFolderPermission -Identity SharingUser":\calendar" -User ShareeUser
        Add-PublicFolderClientPermission -Identity "\pubicFolderName" -AccessRights owner -User User
    
        Add-MailboxPermission SharingUsersMailbox -AccessRights fullaccess,deleteitem -User SharedWithUser -AutoMapping $true
        Remove-MailboxPermission SharingUsersMailbox -AccessRights fullaccess,deleteitem -User SharedWithUser
    
        #endregion
    
        #region SendAs and SendOnBehalf
            #SendAs
            Add-ADPermission -Identity $sharingMailboxID -User SharedWithUser -AccessRights ExtendedRight -ExtendedRights "send as" 
            #SendOnBefalf
            Set-Mailbox sharingMailbox -GrantSendOnBehalfTo sharedWithUser 
            #O365 Sendas
            Add-RecipientPermission Rob.Smith@example.mail.onmicrosoft.com -Trustee me@example.com -AccessRights sendas
            remove-RecipientPermission Rob.Smith@example.mail.onmicrosoft.com -Trustee me@example.com -AccessRights sendas
    
        #endregion
    
        #region Forwarding
        Set-Mailbox -Identity "forwardingMailbox@example.com.au" -ForwardingAddress  "ForwardedToMailbox@example.com.au" -DeliverToMailboxAndForward $true
            #removing Forwarding
            Set-Mailbox -Identity "forwardingingUser" -ForwardingAddress $null -DeliverToMailboxAndForward $false
        #endregion
    
        #region GAL and Address Lists
            #Remove from GAL
            Get-Mailbox removedFromGalMailbox | Set-Mailbox -HiddenFromAddressListsEnabled $true
            #Updating Address lists
            Get-GlobalAddresslist | Update-GlobalAddressList
            Get-AddressList | Update-AddressList
            restart-service MSExchangeFDS
    
        #endregion
    
    
        #region move mailbox
            Get-MoveRequestStatistics John.Doe@example.com
            get-mailbox John.Doe@example.com | New-MoveRequest -TargetDatabase EXBD01
            Get-MoveRequest 
    
        #endregion
    

You can copy between the lines and save this a script it has a break statement at the top to stop it from running you need to modify highlight and run selection to make this work

Extracting First name and Last name out of an email address


        $email = "John.Smith@company.com"
    
        $firstname = $email.Split(".")[0]
        $lnameraw = $email.Split(".")[1]
        $lastName = $lnameraw.Split("@")[0]
        $firstname
        $lastName
        
        John
        Smith
        

Some times you have a list of email addresses and you need to extract First and Last names out of the list to use in a script or report

Connecting to Exchange using the ISE

Connecting to Exchange using the ISE allows you to do Exchange PowerShell tasks with having to log on to the Exchange Server. It also allows you to create and execute scripts on Exchange. The code to do this is as follows:


        $UserCredential = Get-Credential
        $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://ExServer01/PowerShell/ -Authentication Kerberos -Credential $UserCredential
        Import-PSSession $Session -DisableNameChecking -AllowClobber
        

Open you ISE as administrator. Copy the script into it and press f5. You will be prompted for your username and password enter it and press OK. The script will open an implicit remoting session with the exchange server and you can run commands on it.

Connecting to the Exchange ECP for administrative PowerShell Session


    function open-ECP {
                $IE=new-object -com internetexplorer.application 
                $IE.navigate2("https://ex1.company.pri/ecp/")
                $IE.visible=$true
    }

I wrote this script to open the Exchange Control Panel on my computer as an administrator when I am logged on with a regular account. It needs to be run from an administrative shell.

Message tracking log

The message tracking log hold information on messages as tracked by the exchange server. It can be used like this:


    Get-MessageTrackingLog   -Sender User1@OtherCompany.com  -Recipients OurUser@company.pri 
    EventId  Source   Sender                                               Recipients                                        MessageSubject
    -------  ------   ------                                              ----------                                         -------------- 
    HARED... SMTP     user1@othercompany.com                {OurUser@company.pri}                  Message from Unknown sender (00730596354)
    RECEIVE  SMTP     user1@othercompany.com                {OurUser@company.pri}                  Message from Unknown sender (00730596354)
    FAIL     ROUTING  user1@othercompany.com                {OurUser@company.pri}                  Message from Unknown sender (00730596354)
    HAREC... SMTP     user1@othercompany.com                {OurUser@company.pri}                  Message from Unknown sender (00730596354)
    HADIS... SMTP     user1@othercompany.com                {OurUser@company.pri}                  Message from Unknown sender (00730596354)
    

Adding resources to resource mailboxes


Set-Mailbox "Room Mailbox name" -ResourceCustom 'VideoConferenceUnit','ProjectorScreen','ConferencePhone','NetworkConnections','Whiteboard'

You can user the command: "(Get-ResourceConfig).resourcepropertyschema" to find out the allowed resouces that you can add


Creating an out of office message in Exchange


    $message = " 
                right now I am out of the office 
                I will be back later 
                write your own message" 
    
        $useremail = example@company.com
    
        Set-MailboxAutoReplyConfiguration $useremail –AutoReplyState Scheduled –StartTime “14/7/2020” –EndTime “22/7/2020” –ExternalMessage $message –InternalMessage $message
    

Giving a user access to another users calendar

    Set-MailboxfolderPermission -Identity 'calendarowners.name:\calendar' -User "theperson.wantingaccess" -AccessRight owner
    

Giving a user access to another users Mailbox


    Add-MailboxPermission UserWithMailbox -User UserNeedingAccess -AccessRights fullaccess
    

Find the disk space on the exchange servers and outputting it into a html table


    function fnExchangeVolumesFormattedNicely {
        [cmdletbinding()]
        param(
            $ExServer,
            $Path
        )
        
        $r = New-CimSession -ComputerName $ExServer
        $ids = (Get-Volume -CimSession $r ).objectid
        "<html>
            <head>
                <title>$ExServer</title>
                <link rel='stylesheet' href='../styles.css'>
            </head>" | Out-File $Path -Append
        "<h1>Volumes On $ExServer</h1>" | Out-File $Path -Append
        "<table>" | out-file $Path -Append
        "<tr>
            <th>DriveLetter</th>
            <th>FileSystemLabel</th>
            <th>FreeSpace</th>
            <th>DiskSize</th>
        </tr>" | Out-File $Path -Append
        foreach($id in $ids){
            $a = (Get-Volume -ObjectId $id -CimSession $r).DriveLetter  
            $b = (Get-Volume -ObjectId $id -CimSession $r).FileSystemLabel
           $c = "{0:F2}" -f  ((Get-Volume -ObjectId $id -CimSession $r).SizeRemaining  / 1gb)
           $d =  "{0:F2}" -f ((Get-Volume -ObjectId $id -CimSession $r).Size   / 1GB)
           "<tr>
            <td>$a</td>
            <td>$b</td>
            <td>$c</td>
            <td>$d</td>
           </tr>" | Out-File $Path -Append   
        }   
    
        "</table>" | out-file $Path -Append
        "</html>" | out-file $Path -Append
    }
    
    
    fnExchangeVolumesFormattedNicely -ExServer EX1 -Path "c:\temp\ExchangeDiskSpaceEX1.html"
    fnExchangeVolumesFormattedNicely -ExServer EX2 -Path "c:\temp\ExchangeDiskSpaceEX2.html"
    
    Break;