Method Invocation failed because [Deserialized.Microsoft.Exchange.Data.ByteQuantifiedSize] does not contain a method named ‘ToMB’

Scenario: When connecting to Exchange PowerShell without the Exchange management tools installed, you get the following error message when trying to convert the mailbox size to another Size unit.   For example:  With the Exchange Management tools installed,  you can run the following command successfully:

Get-MailboxStatistics  user1 | Select {$_.TotalItemSize.Value.ToMB()}

But when you connect to Exchange Powershell via a session without the Exchange Management tools installed, you receive the following error:

Method Invocation failed because [Deserialized.Microsoft.Exchange.Data.ByteQuantifiedSize] does not contain a method named ‘ToMB’

Solution:  To work around this problem:

#Collect Mailbox Stats
$stat_o365 = get-mailbox -resultsize unlimited | Get-mailboxstatistics

#Loop the stats
$stat_o365 | %{
$Name = $_.displayname
$TIS = [string]$_.TotalItemSize
$TDIS = [string]$_.TotalDeletedItemSize

#start the value manipulation
$regex = [regex]"((.*))"
$TISstring = [regex]::match($TIS, $regex).Groups[1]
$TDISstring = [regex]::match($TDIS, $regex).Groups[1]
$TISString = $TISString -replace "Bytes",""
$TDISString = $TDISString -replace "Bytes",""

#Convert the strings to Int
$TDISValue = [INT]$TDISString
$TISValue =  [INT]$TISString

#Add the Mailbox Size and round to the nearest MB
$TotalSize = [Decimal]::Round((($TDISValue + $TISValue)/1024)/1024)
}

 

 

Powershell method for finding any services that are set to start automatically but have been stopped due to a failure or error.

Scenario: You want a Powershell  method for finding any services that are set to start automatically but have stopped in error or by failure.

Solution:  The script below looks for any Exchange servers that start with 2013* and then uses the logic “Find a Service that is set to Automatic that is currently not running and an Exit Code of the service is not 0” for each server.  Then attempt to restart that service on each server.   An exit code of 0 means the service was stopped manually OR stopped by Windows as it was no longer required to run. Here is a list of Error Code/Exit Code descriptions: Exit Code Descriptions

 

#Collect Servers into a Variable
$1 = Get-exchangeserver 2013*

#Collect Services that are not started due to failure or error
$2 = $1 |%{Get-CimInstance win32_service -Filter "startmode = 'auto' AND state != 'running' AND Exitcode !=0 " -ComputerName $_ | select systemname, name, startname, exitcode}

#View the Services that are stopped for each server
$2

#Restart each failed service
$2 | %{Get-service $_.Name -computername $_.SystemName | Start-service -passthru}

Perform a search mailbox to specific mailbox items between a date range.

Scenario: You want to non-invasively search a mailbox in order to find content between a date range.

Solution:  Run the following command(s):

search-mailbox userid -searchquery “kind:Email AND Received:1/1/1900..08/01/2014” -EstimateResultOnly

Note: You can remove estimateresultonly and replace with TargetMailbox and TargetFolder to export the queried contents of the mailbox to view the messages.  You can also use the following KIND variables to target certain message types in your search:

Email
Meetings
Tasks
Notes
Docs
Journals
Contacts
IM

Script to determine Exchange ActiveSync devices and email the report

Scenario:  You want a script that will perform the following:

  1. Provide all device statistics in csv format attached to the email report.
  2. Provide a total of Devices in the email report
  3. Provide a total of mailboxes that have a device in the email report
  4. The average number of devices per user in the email report
  5. Provide a list of devices that have not connected in over 6 months in the email report
  6. Provide a count for each ActiveSync policy applied on all mailboxes in the email report
  7. Provide a list of the top 10 device types in the email report
  8. Provide a list of the top 10 users based on device count in the email report

Script: 

#Define Variables
    $age = 180
    $final_DeviceCount = @()
    $report = @()
    $file = $(((get-date).ToUniversalTime()).ToString("yyyyMMddThhmmssZ"))
    $filename = "C:tempeas_stat_"+$file+".csv"
    $today = get-date
    $final = @()
    $BreakLine = "
    "
 $stats = @("FirstSyncTime",
        "LastPolicyUpdateTime",
        "LastSyncAttemptTime",
        "LastSuccessSync",
        "DeviceType",
        "DeviceID",
        "DeviceUserAgent",
        "DeviceWipeSentTime",
        "DeviceWipeRequestTime",
        "DeviceWipeAckTime",
        "LastPingHeartbeat",
        "RecoveryPassword",
        "DeviceModel",
        "DeviceImei",
        "DeviceFriendlyName",
        "DeviceOS",
        "DeviceOSLanguage",
        "DevicePhoneNumber",
        "MailboxLogReport",
        "DeviceEnableOutboundSMS",
        "DeviceMobileOperator",
        "Identity",
        "Guid",
        "IsRemoteWipeSupported",
        "Status",
        "StatusNote",
        "DeviceAccessState",
        "DeviceAccessStateReason",
        "DeviceAccessControlRule",
        "DevicePolicyApplied",
        "DevicePolicyApplicationStatus",
        "LastDeviceWipeRequestor",
        "ClientVersion",
        "NumberOfFoldersSynced",
        "SyncStateUpgradeTime",
        "ClientType",
        "IsValid",
        "ObjectState"
          )

#Define Email Variables:
    $smtp = "smtp.domain.com"
    [string[]]$to = "steve@domain.com"
    $from = "MobileDeviceStats@domain.com
    $subject = "Mobile Device Stats using ActiveSync"

#Define HTTP Style
$b = "<style>
        BODY{
        font-family: Arial; font-size: 10pt;
        }
        TABLE{
        border: 1px solid black; border-collapse: collapse;
        }
        TH{
        border: 1px solid black; background: #dddddd; padding: 5px;
        }
        TD{
        border: 1px solid black; padding: 5px;
        }
    </style>"
#=========Begin Script===========
#Calculate Mailboxes with EAS Device Partnership
$MailboxesWithEASDevices = @(Get-CASMailbox -Resultsize Unlimited -erroraction SilentlyContinue | Where {$_.HasActiveSyncDevicePartnership} | Select Identity,SAMAccountName)
$MailboxesWithEASDevices = $MailboxeswithEasDevices | Sort SAMAccountName
#Loop Through Each Mailbox
Foreach ($Mailbox in $MailboxesWithEASDevices)
{
$EASDeviceStats = @(Get-MobileDeviceStatistics -Mailbox $Mailbox.Identity)
Write-Host "$($Mailbox.SAMAccountName) has $($EASDeviceStats.Count) device(s)"
#Build the Array
   $ServerObj = New-Object PSObject
   $ServerObj | Add-Member NoteProperty -Name "Alias" -Value $Mailbox.SAMAccountName
   $ServerObj | Add-Member NoteProperty -Name "DeviceCount" -Value $EASDeviceStats.Count
   $Final_DeviceCount += $ServerObj   
$MailboxInfo = Get-Mailbox $Mailbox.Identity | Select DisplayName,PrimarySMTPAddress,Alias
Foreach ($EASDevice in $EASDeviceStats)
    {$LastSuccessSync = ($EASDevice.LastSuccessSync)
 if ($LastSuccessSync -eq $null)
        {
            $syncAge = "Never"
        }
        else
        {
            $syncAge = ($today - $LastSuccessSync).Days
        }
       $reportObj = New-Object PSObject
       $reportObj | Add-Member NoteProperty -Name "DisplayName" -Value $MailboxInfo.DisplayName
       $reportObj | Add-Member NoteProperty -Name "EmailAddress" -Value $MailboxInfo.PrimarySMTPAddress
       $reportObj | Add-Member NoteProperty -Name "Alias" -Value $MailboxInfo.Alias
       $reportObj | Add-Member NoteProperty -Name "SyncAgeInDays" -Value $syncAge
            Foreach ($stat in $stats)
            {
                $reportObj | Add-Member NoteProperty -Name $stat -Value $EASDevice.$stat
            }
            $report += $reportObj
        }    
}
$report | Export-csv $filename
$TotalDevices = $report.count
$TotalMailboxes = $MailboxesWithEASDevices.Count
$AvgPerMailbox = $TotalDevices / $TotalMailboxes
$LastSync180  = ($Report | Where SyncAgeInDays -ge $age).count
$Top10DeviceTypes = $Report | group DeviceType | Sort Count -Descending | Select Count,Name -first 10 | ConvertTo-Html -head $b
$Top10Users = $final_DeviceCount | Sort DeviceCount -Descending | Select Alias,DeviceCount -first 10 | ConvertTo-Html -head $b
$PolicyApplied = $report | Group DevicePolicyApplied | Sort Count -Descending | Select Count,Name | ConvertTo-Html -head $b
$body =""
$attachment = $filename
$body += "<Font color=black>Attached are the Mobile Device Statistics within the entire OnPremise Exchange Organization using ActiveSync.</font><br><br><br>"
$body += "<b><Font color=#00008B>Total devices:</b><Font color=black> $TotalDevices</font><br><br>"
$body += "<b><Font color=#00008B>Total mailboxes that have a device:</b><Font color=black> $TotalMailboxes</font><br><br>"
$body += "<b><Font color=#00008B>Average Devices Per User:</b><Font color=black> $AvgPerMailbox</font><br><br>"
$body += "<b><Font color=#00008B>Devices with last sync time older than $age days:</b><Font color=black> $LastSync180</font><br><br>"
$body += "<b><Font color=#00008B>ActiveSync policy applied on all mailboxes:</b> $PolicyApplied</font><br><br>"
$body += "<b><Font color=#00008B>Top 10 device types:</b></font><br><br>"
$body += "<Font color=black>$Top10DeviceTypes</font><br><br><br>"
$body += "<b><Font color=#00008B>Top 10 users by device count:</b></font><br><br>"
$body += "<Font color=#00008B>$Top10Users</font><br><br><br>"
send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $body -BodyAsHtml -Priority high -Attachments $attachment

#=========End Script===========

Cannot access the C$ on one of your Windows Server 2012 servers

Scenario:  Your server is experiencing networking issues that appear local to the Server OS.  The symptoms experienced:

  1. Although you can successfully ping the server, you cannot access the c$ or other shares hosted off the server. Your error message talks about not having the appropriate permissions AND/OR the server not being available on the network.
  2. Although you can see the network adapters in Device Manager, you cannot see the network adapters in the Network & Sharing center via control panel.

Cause:  Network Adapter Corruption

Solution:  Uninstalling and Reinstalling the network driver on the server.  Below are other troubleshooting steps that may help:

Our Troubleshooting Steps:

  1. We found EventID 10016 in the System Log.  (Microsoft-Windows-DistributedCOM)
  2. We started testing if there is corruption with the Config Key. We  deleted the Config key from the registry: HKLM/System/currentcontrolset/Control/Network/Config ,config.  This key holds all of the Network card information. Once you reboot, it creates a new key in same registry with proper settings.
  3. After reboot we found that the config key was there ,but the server lost network connection completely.
  4. We tried assigning static IP using netsh via the command prompt but that resulted in the error: Element not found.
  5. That made us believe that the network database is corrupted.
    We uninstalled the Network Drivers and network card from device manager rebooted the server.
  6. Installed the new drivers back that resulted in server to function properly.

Removing Exchange Databases Manually from AD

Scenario:  When you attempt to run Get-MailboxDatabase -includePreExchange2013, you get the following error:

The Exchange server for the database object ‘DB11’ wasn’t found in Active directory Domain Services. The object may be corrupted.

You then discovered the mailbox server that used to host the database no longer exists in your organization and was forcibly removed via ADSIEdit.

Resolution:  Remove the orphaned databases via ADSIEdit:

  1. Open ADSIEdit.
  2. Navigate to Configuration –> Configuration –>Services –> Microsoft Exchange –> Enterprise Exchange –> Administrative Groups –> Exchange Administrative Groups –> Databases.
  3. Locate the database and delete it.

Reconnect an Exchange 2013 Mailbox

Scenario:  A mailbox is disabled from an AD user account but it’s still present in Exchange as a disconnected Mailbox.  To view the disconnected mailbox:   Get-MailboxStatistics | Where DisconnectDate -ne $null

Resolution:  Run the following commands:

Connect-Mailbox “Display Name” -Database “DB Name” -user “AD User Object Name”

Example:

Connect-Mailbox “John Jacob” -Database DB03 -user “jjacob”

Exchange Script to Export Hardware Inventory and Exchange Settings

Scenario:    You want to export hardware inventory and Exchange settings from your Exchange Organization.

Script:  You can copy all the script parts and run at once OR run each script part separately depending on what you want to achieve.  You could also build on to this script using the same format with different get commands.

 

#Specify Variables
$today = (get-date -f yyyy-MM-dd)
$Folder = "C:TempCollection"
#Pull Exchange Server Hardware Inventory
$Servers = Get-ExchangeServer
$Servers | Export-csv $folder$today-Get-ExchangeServer.csv
($servers).name | Out-File $folder$today-Servers.txt
$serverList = "$folder$today-Servers.txt"
$outputCSV = "$folder$today-ServerInventory.csv"
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
pushd $dir
[System.Collections.ArrayList]$sysCollection = New-Object System.Collections.ArrayList($null)
foreach ($server in (Get-Content $serverList))
{
    "Collecting information from $server"
    $totCores=0
  
    try
    {
        [wmi]$sysInfo = get-wmiobject Win32_ComputerSystem -Namespace "rootCIMV2" -ComputerName $server -ErrorAction Stop
        [wmi]$bios = Get-WmiObject Win32_BIOS -Namespace "rootCIMV2" -computername $server
        [wmi]$os = Get-WmiObject Win32_OperatingSystem -Namespace "rootCIMV2" -Computername $server
        #[array]$disks = Get-WmiObject Win32_LogicalDisk -Namespace "rootCIMV2" -Filter DriveType=3 -Computername $server
        [array]$disks = Get-WmiObject Win32_LogicalDisk -Namespace "rootCIMV2" -Computername $server
        [array]$procs = Get-WmiObject Win32_Processor -Namespace "rootCIMV2" -Computername $server
        [array]$mem = Get-WmiObject Win32_PhysicalMemory -Namespace "rootCIMV2" -ComputerName $server
        [array]$nic = Get-WmiObject Win32_NetworkAdapterConfiguration -Namespace "rootCIMV2" -ComputerName $server | where{$_.IPEnabled -eq "True"}
  
        $si = @{
            Server          = [string]$server
            Manufacturer    = [string]$sysInfo.Manufacturer
            Model           = [string]$sysInfo.Model
            TotMem          = "$([string]([System.Math]::Round($sysInfo.TotalPhysicalMemory/1gb,2))) GB"
            BiosDesc        = [string]$bios.Description
            BiosVer         = [string]$bios.SMBIOSBIOSVersion+"."+$bios.SMBIOSMajorVersion+"."+$bios.SMBIOSMinorVersion
            BiosSerial      = [string]$bios.SerialNumber
            OSName          = [string]$os.Name.Substring(0,$os.Name.IndexOf("|") -1)
            Arch            = [string]$os.OSArchitecture
            Processors      = [string]@($procs).count
            Cores           = [string]$procs[0].NumberOfCores
            NIC      = [string]$nic[0].IPAddress
        }
         
        $disks | foreach-object {$si."Drive$($_.Name -replace ':', '')"="$([string]([System.Math]::Round($_.Size/1gb,2))) GB"}
    }
    catch [Exception]
    {
        "Error communicating with $server, skipping to next"
        $si = @{
            Server          = [string]$server
            ErrorMessage    = [string]$_.Exception.Message
            ErrorItem       = [string]$_.Exception.ItemName
        }
        Continue
    }
    finally
    {
       [void]$sysCollection.Add((New-Object PSObject -Property $si))   
    }
}
 
$sysCollection `
    | select-object Server,NIC,TotMem,OSName,Arch,Processors,Cores,Manufacturer,Model,BiosDesc,BiosVer,BiosSerial,DriveA,DriveB,DriveC,DriveD,DriveE,DriveF,DriveG,DriveH,DriveI,DriveJ,DriveK,DriveL,DriveM,DriveN,DriveO,DriveP,DriveQ,DriveR,DriveS,DriveT,DriveU,DriveV,DriveW,DriveX,DriveY,DriveZ,ErrorMessage,ErrorItem `
    | sort -Property Server `
    | Export-CSV -path $outputCSV -NoTypeInformation  
#Export ClientAccess Settings
$CASServers = Get-ClientAccessServer 
$CASServers | %{Get-OWAVirtualDirectory -server $_.name  | Export-csv $folder$today-Get-OWAVirtualDirectory.csv -append}
$CASServers | %{Get-ECPVirtualDirectory -server $_.name  | Export-csv $folder$today-Get-ECPVirtualDirectory.csv -append}
$CASServers = Get-ClientAccessServer 
$CASServers | %{Get-OWAVirtualDirectory -server $_.name  | Export-csv $folder$today-Get-OWAVirtualDirectory.csv -append}
$CASServers | %{Get-ECPVirtualDirectory -server $_.name  | Export-csv $folder$today-Ge$CASServers | %{Get-OABVirtualDirectory -server $_.name  | Export-csv $folder$today-Get-OABVirtualDirectory.csv -append}
$CASServers | %{Get-MAPIVirtualDirectory -server $_.name  | Export-csv $folder$today-Get-MAPIVirtualDirectory.csv -append}
$CASServers | %{Get-WebServicesVirtualDirectory -server $_.name  | Export-csv $folder$today-Get-ServicesVirtualDirectory.csv -append}
$CASServers | %{Get-ActivesyncVirtualDirectory -server $_.name  | Export-csv $folder$today-Get-EASVirtualDirectory.csv -append}
$CASServers | %{Get-OutlookAnywhere -server $_.name | Export-csv $folder$today-Get-OutlookAnywhere.csv -append}
#Export Database Settings
$DB = Get-mailboxdatabase 
$DB | Export-csv $folder$today-Get-MailboxDatabase.csv -append
#Export DAG Settings
$DAG  = Get-DatabaseAvailabilityGroup 
$DAG | Export-csv $folder$today-Get-DatabaseAvailabilityGroup.csv

Determine what roles are needed to run specific commands when determining Role Groups

Scenario:  You want to provide only the roles necessary to a new role group based on the Exchange Shell commands that need to be ran.

Solution:  Run the following to determine which roles will need to be added to the role group:

Get-ManagementRoleEntry *Set-ActiveSyncMailboxPolicy  | Select Name,Role

Name                           Role
Set-ActiveSyncMailboxPolicy    Recipient Policies

Configure Exchange Certificate Based Authentication for Exchange ActiveSync

Scenario:  You want to enable Certificate Based Authentication for Exchange ActiveSync. TMG is already setup and configured to accept/process he CBA ActiveSync request. Now we need to configure Exchange so it can successfully accept the trusted authenticated hand off from TMG.
Our Environment:
 Exchange: Exchange 2013 SP1
Server:  Windows Server 2012
MDM:  Airwatch (Needed to push out the Certificates)
 We currently have and will keep servers that will process activesync via Basic Authentication with the server name: mail.domain.com. We have separate servers will process activesync via CBA with the servername: mailcba.domain.com.
Configuration Steps:
Exchange Certificate:
1. Add the new external and internal server names that will be used to point activesync devices to EAS CBA as an subject alternate name to the existing server. Currently you may use mail.domain.com as the server name for Exchange ActiveSync that processes Basic Authentication.  You will need a separate server name, such as mailcba.domain.com, that will be used to allow the TMG accept and pass this traffic to the new servers.  Also you need to include the internal server name as an subject alternative name.
 2. Import the Exchange certificate in Exchange and apply the IIS service to it.
Add Roles to Server:
3. Install the Client Certificate Mapping Authentication Role. In PowerShell run:
Import-Module ServerManager
Add-WindowsFeature Web-Client-Auth
 
ActiveSync Virtual Directory:
4. Remove Basic Authentication and Select Accept Client Certificate.
     a. Open Exchange EAC.
b. Navigate to Servers–>Virtual Directories
c. Open the ActiveSync Virtual Directory on the server you wish to enable Certificate Based Authentication.
d. Uncheck Basic Authentication and mark Accept Client Certificates.
 5. Add the Internal and External URLs accordingly, example: internalurl/externalurl: mailcba.domain.com  (Note: Becareful of AutoDiscover. If you have the option of not including this server for Autodiscover lookups for ActiveSync, mobile devices should not receive these server settings when they want to authenticate via Basic.  Else, you could set the internalurl/externalurl on the CBA virtual directories to the same urls as the ones accepting basic auth.
IIS Manager:
5. Enable Active Directory Client Certificate Authentication on the Server.
a. Open IIS Manager.
b. Click on the Server Name.
c. Click on Authentication
d. Enable Active Directory Client Certificate Authentication
e. Restart IIS Admin Service in Services console.
 6. Enable Client Certificate Mapping Authentication on the ActiveSync Virtual Directory.
a. From an elevated command prompt, navigate to C:windowssystem32inetsrv.
b. Enter in the following:
APPCMD.EXE set config “Default Web Site/Microsoft-Se
rver-ActiveSync” -section:system.webServer/security/authentication/clientCertificateMappingAuthentication /enabled:”True” /commit:apphost
 7. Change the UploadReadAheadSize from its default value (0) to the max size you wish to send from a activesync device. For example, if your sending limits is 35MB, the value will be 36700160.
a. Open IIS Manager.
b. Navigate to the Microsoft-Server-ActiveSync virtual directory.
c. Click on Configuration Editor.
d. Navigate to system.webserver/serverRuntime.
e. Edit the Value of uploadReadAheadSize to 36700160 and apply it.
 8.  Enable Windows Authentication on the Microsoft-Server-ActiveSync virtual Directory. (this is for TMG)
a. Open IIS Manager.
b. Navigate to the Microsoft-Server-ActiveSync virtual directory.
c. Click on Authentication.
d. Enable Windows Authentication.
 9.  Restart World Wide Web services from the services console.