Cleanup Mobile Devices older than 180 Days

Scenario:  You want a script that will remove all mobile devices older than 180 days.  You also want to report the CAS Mailboxes that have a mobile device partnership and the list of mobile devices removed.

Scriptlets:

Here are the commands broken down by output type:

#Collect CasMailboxes with Mobile Devices
$cas = Get-CASMailbox -ResultSize unlimited –Filter {(HasActiveSyncDevicePartnership -eq $true)} | Select -expandproperty Identity

#Export a List of Cas Mailboxes
$cas | Sort | Export-csv C:tempCASmailbox.csv 

#Collect devices older than 180 days old
$device = @()
$cas | sort | %{
"Checking $_" 
$device += Get-MobileDeviceStatistics -Mailbox $_ | Where-Object {$_.LastSuccessSync -le ((Get-Date).AddDays(“-180”))} 
}

#Export-csv Stale Devices
$Device | Export-csv C:tempStaleDevices.csv

#Remove Mobile Devices
$Device | Remove-mobiledevice -confirm:$false

 

 

 

 

 

 

Outlook’s Autodiscover Redirect Limit – Hybrid Autodiscover Breaking for Exchange Online Mailboxes / Remote On-Premises Mailboxes

Scenario:  After introducing additional Exchange On-Premises servers, we noticed that Autodiscover stopped working for our Exchange Online Hybrid mailboxes that were on computers internal to the domain. Using the ‘Test E-mail AutoConfiguration’ feature in Outlook, it would fail after the SCP/DNS autodiscover lookup.

Reason:  Outlook has an Autodiscover Redirect limit of 8-10 responses.  Being we had more than 10 servers in our Exchange Infrastructure, once it hit the response limit from each SCP lookup for each server, it would then fail all redirects thereafter. You do not need 100 SCP Failures if its going to fail after the first 10 servers.

Solution:  You can reduce the number of SCP lookup’s by performing any of the following.

  1. Set the AutoDiscoverSiteScope value on each Exchange server so it only serves requests for each  AD Site via the following command:  Set-ClientAccessServer ExSrv1 -autodiscoversitescope NewYork   (Or a combination NewYork,Baltimore,Tampa)
  2. Set the AutoDiscoverSiteScope to $null so it does not participate in SCP lookups via the following command: Set-ClientAccessServer ExSrv1 -AutodiscoverSiteScope $null
  3. Set the AutoDiscoverServiceInternalURI to $null so it does not participate in SCP lookups via the following command: Set-ClientAccessServer ExSrv1 -AutodiscoverServiceInternalURI $null

 

Determine the effective management roles assigned to an Exchange Administrator

Scenario: You want to view/verify the management roles assigned to Exchange Administrators.

Scriptlet:

To view a list of management roles for every Exchange Administrator, run:

Get-ManagementRoleAssignment -GetEffectiveUsers

If you are looking for a specific user, run:

Get-ManagementRoleAssignment -GetEffectiveUsers | Where { $_.EffectiveUserName -like “steveadm1” }

Send on Behalf not working Externally

Scenario:  When ‘Sending on Behalf’ to an internal recipient, the sender displays correctly/as expected:

Steven on behalf of TestService123

BUT, when “Sending on Behalf” to an external recipient, the result of the sender line displaying correctly is unpredictable.  It may only show the email address of the sender you sent on behalf of and may not include your delegated email address.

TestService123 (TestService123@domain.com)

Reason:  The “Send on Behalf” feature is an Exchange feature.  Unless your external mail system knows how to process the headers ‘From’ and ‘Sender’ lines, it may only show it coming from the ‘From’ address, the email address you sent on behalf from and not include your delegated email address.

PowerShell Script: Combine the Alias and Mailbox Size into a variable and export to a file.

Scenario:  You want a script that will combine the Alias from the get-mailbox command and the Mailbox Size (TotalItemSize and TotalDeletedItemSize) from the get-mailboxstatistics command into a single array variable.  You want to export the Results to a .csv file as well.

Script:

$db = get-mailboxdatabase 
$final = @()
$file = "C:tempAlias_Size.csv"

$db | Select -expandproperty Name | Sort | %{
    Write-Host "DBName:  $_ " -ForegroundColor Cyan
    $mbx = Get-mailbox -database $_ -resultsize unlimited
    $mbx | Select -expandpropert alias | Sort | %{
        Write-Host ".......... Pulling Stats for $_" -ForegroundColor Yellow
        $alias = $_
        $size = Get-mailboxstatistics $alias | Select TotalItemSize,TotalDeletedItemSize
        $TIS = $size.TotalItemSize
        $TDIS  = $size.TotalDeletedItemSize
        $ServerObj = New-Object PSObject
        $ServerObj | Add-member NoteProperty -Name "Alias" -Value $alias
        $ServerObj | Add-Member NoteProperty -name "TIS" -Value $TIS
        $ServerObj | Add-Member NoteProperty -name "TDIS" -Value $TDIS
        $final += $ServerObj
    }
}
$final | Export-csv $file -append

 

EWS Script: Recover Email Items out of the Purges and Deletions based on a timeframe for when the email items were deleted.

Scenario:  You want to recover email items that were deleted from the mailbox and were moved into the backend Purges and Deletions Recoverable folders. You want to recover only items that were deleted  between a timeframe. You also want to place these deleted items into a single folder available in the mailbox.

Scriptlets:

Declare your Variables:

#Variables
    $cred = Get-credential  #credentials will fullaccess to access the mailbox
    $mailboxname = "Jane@Domain.Com"  #The Mailbox you wish to perform the query and restore on
    $EWS_DLL = "C:Program FilesMicrosoftExchange ServerV15BinMicrosoft.Exchange.WebServices.dll"
    $EWS_URL = "https://mail.domain.com/ews/exchange.asmx"
    [datetime]$StartDate  = "6/5/2017" #Used for the LastModifiedTime
    [datetime]$EndDate = "6/19/2017" #Used for the LastModifiedTime
    $RestoreFolder = "Recovered Items"  #The folder thats is already created in the mailbox to restore to

Configure the EWS connection properties

#Configure connection to EWS
    Import-Module -Name $EWS_DLL
    $service = new-object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.Exchangeversion]::exchange2013)
    $service.Url = new-object System.Uri($EWS_URL)
    $service.UseDefaultCredentials = $false
    $service.Credentials = $cred.GetNetworkCredential()

Attach to the following folders:  Purges, Deletions, and Recoverable Items (created in mailbox to restore content to)

#Attach to Purges
    $folderidpurges = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::RecoverableItemspurges,$MailboxName)
    $purgesFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderidpurges)
#Attach to Deletions
    $folderidDeletions = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::RecoverableItemsDeletions,$MailboxName)
    $DeletionsFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderidDeletions)
#Attach to Recovered Items Folder
    $PathToSearch = $restorefolder  
    $folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$mailboxname)   
    $tfTargetFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
    $fldArray = $PathToSearch.Split("") 
    for ($lint = 1; $lint -lt $fldArray.Length; $lint++) { 
        $fldArray[$lint] 
        #Perform search based on the displayname of each folder level 
        $fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1) 
        $SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,$fldArray[$lint]) 
        $findFolderResults = $service.FindFolders($tfTargetFolder.Id,$SfSearchFilter,$fvFolderView) 
        if ($findFolderResults.TotalCount -gt 0){ 
            foreach($folder in $findFolderResults.Folders){ 
                $tfTargetFolder = $folder                
            } 
        } 
        else{ 
            "Error Folder Not Found"  
            $tfTargetFolder = $null  
            break  
        }     

Create your Search Filter and perform the search

#Create and Apply an Search Filter
    $sfCollection = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+SearchFilterCollection([Microsoft.Exchange.WebServices.Data.LogicalOperator]::And);
    $Sfgt = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsGreaterThan([Microsoft.Exchange.WebServices.Data.ItemSchema]::LastModifiedTime, $StartDate)
    $Sflt = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsLessThan([Microsoft.Exchange.WebServices.Data.ItemSchema]::LastModifiedTime, $EndDate)
    $sfCollection.add($Sfgt)
    $sfCollection.add($Sflt)
    $view = new-object Microsoft.Exchange.WebServices.Data.ItemView(2000000)
    $miMailItems = $DeletionsFolder.FindItems($sfCollection,$view)

Lastly,  Move your email Items into the Recovery folder

    ###Moves your Email Items
    $MiMailItems | %{
        "Moving: "+ $_.LastModifiedTime +": " + $_.Subject.ToString()
        [VOID]$_.Move($tftargetfolder.id)
    }

 

 

 

 

 

 

 

 

 

Powershell: List all mailbox folder delegate access for a mailbox

Scenario: You want to determine all mailbox folder delegate access for a mailbox. You wish to not include the anonymous and default permissions.

Script:

$mbx = "steve"
$permissions = @()
$Folders = Get-MailboxFolderStatistics $mbx | % {$_.folderpath} | % {$_.replace(“/”,””)}
$list = ForEach ($F in $Folders)
   {
    $FolderKey = $mbx + ":" + $F
    $Permissions += Get-MailboxFolderPermission -identity $FolderKey -ErrorAction SilentlyContinue | Where-Object {$_.User -notlike “Default” -and $_.User -notlike “Anonymous” -and $_.AccessRights -notlike “None”}
   }
$permissions

EWS Script: Monitor EWS is working properly by querying for an email item on a timely basis

Scenario:  After your frontend client access gateway has crashed a couple of times, you would like to test that your frontend client access gateway continues to work properly for EWS. You would like an EWS script to validate that not only can it login to a mailbox, but it can query for a specific item in the mailbox.   If it cannot query for the email item in the mailbox, then you want to be notified.

Script:

  1. First create a mailbox that you will monitor.
  2. Send an email to that mailbox so you can query that email by the subject line.

Create your Variables:

#Mailbox Variables
$MailboxName = "EWSMonitor@Domain.com #Mailbox to Query
$Subject = "EWS Test" #Message to query


#Script Variables
$cred1 = get-credential  #This account has access to the mailbox
$Counter = 0 #If you want the counter to stop after # of loops
$sleep = 600 #10 minutes
$EndLoop = "Run Forever" #Set as value so it stops in a timely manor


#Email Variables
[string[]]$to = "steve@domain.com","billy@domain.com"
$smtp = "mail.domain.com"
$from = "EWS_Monitor@domain.com"
$subject1 = "EWS FAILURE" 


The Looping Script

#Loop#############################################
Do{
    $miMailItems = $null
    "Starting Loop"
    $Counter++
    #Connect to EWS
    Import-Module -Name "C:Program FilesMicrosoftExchange ServerV15BinMicrosoft.Exchange.WebServices.dll"
    $service = new-object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.Exchangeversion]::exchange2013)
    $service.Url = new-object System.Uri("https://email.domain.com/EWS/Exchange.asmx")
    $service.UseDefaultCredentials = $false
    $service.Credentials = $cred1.GetNetworkCredential()
    #Attach to Inbox
    $folderidInbox = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)
    $InboxFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderidInbox)
    #Search Filter
    $Sfsub = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject, $Subject)
    $sfCollection = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+SearchFilterCollection([Microsoft.Exchange.WebServices.Data.LogicalOperator]::And);
    #Build your Search Collection
    $sfCollection.add($Sfsub)
    $view = new-object Microsoft.Exchange.WebServices.Data.ItemView(2000000)
    $miMailItems = $InboxFolder.FindItems($sfCollection,$view)
    "Found MailItem in StaciATest = $($MiMailItems.count)"
    If($MiMailItems.count -NE 1){      
        "MailItem Count -eq Null, Sending Message"
        send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject1 -Priority high
         }
   "Sleeping $Sleep"
    Sleep $sleep
}While($Counter -ne $EndLoop)
#####################################################################################

 

 

 

Remotely configure a certificate after importing the new certificate to your Exchange Servers

Scenario:  You imported a new certificate to your Exchange servers and you want to configure the certificate on each server remotely.  There is OWA/LYNC integration and the thumbprint of the older certificate needs to be updated with the thumbprint of the new certificate for the IMCertificateThumbprint property in each servers OWA web.config file.

Scriptlets:

Declare your variables for the Servers and for the thumbprints of the Old and New Cert.

#Declare Variables
$OldCert = "B8FE4323EEdAAB31258C2F44283001004EEACB23"
$NewCert = "A8E457DE801F7831317C2F5F5450007EA238DDE3"
$Servers = Get-exchangeserver Ex* | Select -ExpandProperty Name

We are going to backup the web.config file as well in the event of a mistake.

#Backup Web.Config and Save it locally
$Servers | %{
"Copying $_"
MD C:TempWebConfig$_
Copy-item "\$_c$Program FilesMicrosoftExchange ServerV15ClientAccessOwaweb.config" "C:TempWebConfig$_"
}

Because OWA/LYNC integrations exists, we need to modify the IMCertificateThumbprint OWA Web.Config file so it updates/overwrites the old thumbprint with the new thumbprint.

#Edit the Web.Config on each Server
$Servers | Sort | %{
"Editing WebConfig for $_"
$WebConfigFile = "\$_c$Program FilesMicrosoftExchange ServerV15ClientAccessOwaweb.config"
(Get-Content $webconfigfile).replace('$OldCert', 'NewCert') | Set-Content $Webconfigfile
}

Enable the Services on the new Certificate

#Enable UM, IIS, SMTP, UMCallRouter on new Cert
$Servers | %{
Enable-ExchangeCertificate -Server $_ -thumbprint $NewCert -services IIS,SMTP,UM,UMCallRouter -force -confirm:$false
}

Finally, Restart IIS & UM Services on each server

#Restart IIS & UM Services
$Servers | %{
iisreset $_
get-service msexchangeUM* -computername $_ | Restart-service
}

 

Install Microsoft Unified Communications Managed API 4.0 Remotely Via PowerShell

Scenario:  You want to install Microsoft’s Unified Communications Managed API 4.0 to multiple servers remotely

Script:

  1. Collect your Servers by Querying AD
Import-Module ActiveDirectory
$strOU = "OU=Exchange2016,DC=XYZ,DC=COM"
$servers = get-adcomputer -searchbase $strOU -properties Name -Filter *|  where {$_.name -like "Ex16-*"} | Select -ExpandProperty Name

2. Copy your Installer File to a folder on each server (or a single network share). We have copied it to C:softwareUCMA.exe on each Exchange Server.

3. Run the Installer by invoking the command on each server.

$servers | %{"Installing UCMA on $_"; Invoke-Command -Computer $_ -ScriptBlock {
    #Set Variables
    $file = "C:softwareUcma.exe" 
    #check to see if its installed
    if (Get-ItemProperty "HKLM:SoftwareMicrosoftWindowsCurrentVersionUninstallUCMA4" -ErrorAction SilentlyContinue) { 
        Write-host "Unified Communications Managed API 4.0 Runtime is already installed." -ForegroundColor Cyan 
        } else {
               #testing
               If (Test-Path $file){ 
                    Write-host "The installer file exists:$file"  -ForegroundColor Green
                     #Installing
                     Write-Host "Installing Microsoft UM API..." -ForegroundColor yellow 
                     $arg = "/quiet /norestart" 
                     $status = (Start-Process $file -ArgumentList $arg -Wait -PassThru).ExitCode 
                     if ($status -eq 0) { write-host "Successfully installed $file" -ForegroundColor Green } 
                     if ($status -ne 0) { write-host "Failed!" -ForegroundColor Red }                           
            } else {Write-host "$file does not exist" -ForegroundColor red}
}
}}