Powershell to Customize Exchange 2007 Online Maintenance

Powershell to customize online maintenance schedule. During this interval, tasks like dumpster cleanup (the deletion of messages that have passed their deleted item retention date), deleted mailbox cleanup, and online defragmentation (database objects that are no longer being used are detected and removed, thereby making additional database space available) are performed. These processes keep the Exchange Server computer healthy and the performance stable. Online maintenance should be set to run at least four hours a day; failing to do so will cause performance degradation over time.

Get-MailboxDatabase | Set-MailboxDatabase -MaintenanceSchedule “Sun.1:00 PM-Sun.5:00 PM”,”Mon.1:00 PM-Mon.5:00 PM”, “Tue.1:00 PM-Tue.5:00 PM”, “Wed.1:00 PM-Wed.5:00 PM”,”Thu.1:00 PM-Thu.5:00 PM”, “Fri.1:00 PM-Fri.5:00 PM”,”Sat.1:00 PM-Sat.5:00 PM”

PowerShell to Create New Mailboxes in the smallest database in Exchange 2007 Organization

Loadbalance of the Exchange Database is very important. We need to make sure that  database is not dumped with all the mailbox and once database gets big then move maiboxes to the other database. We can automate this process buy make the script to find the smallest size of the database in the Exchange orginisation and create the mailbox in the same

$MailboxSvr = Get-MailboxServer | select name
$i = 0
foreach($svr in $mailboxsvr)
 {
  $db = Get-MailboxDatabase -Server $svr.Name
  
  foreach($database in $db)
   {
    $Server = $database.Server.Name
    $Db = $database.Identity
    $edbfilepath = $database.EdbFilePath
  
    $path = “`\`\” + $Server + “`\” + $edbfilepath.DriveName.Remove(1) + “$”+ $edbfilepath.PathName.Remove(0,2)
    $Dbsize =  get-item $path |select-object length
    $K = $Server + ” ” + $Db + ” ” + $Dbsize.Length
    if ($i -eq 0 )
     {
     
     $edbsize = $Dbsize.Length
     }
    
    If ($edbsize -gt $Dbsize.Length)
    {
       $edbsize = $Dbsize.Length  
     $sdb = $database.Identity
    } 

    $i = 1
       
   }
    
    
 }
 
Write-output “ENTER THE FOLLOWING DETAILS”
$DName = Read-Host “User Diplay Name  ”
$FName = Read-Host “First Name ”
$LName = Read-Host “Last Name ”
$passwd = Read-Host “Password ” -asSecureString
$PrincipalName = $FName + “.” + $LName + “@domain.com”
$Aliasname = $FName + “.” + $LName
New-Mailbox -Name $DName -Database $sdb -UserPrincipalName $PrincipalName -FirstName $FName -LastName $LName -Alias $Aliasname -Password $passwd -ResetPasswordOnNextLogon $true -SamAccountName $Aliasname

 

You can get the complete copy of the code in the below link file

http://powershell.com/cs/cfs-filesystemfile.ashx/__key/CommunityServer.Components.UserFiles/00.00.00.30.62/NewMailbox_5F00_SmalletDatabase.txt

Powershell to apply Fullaccess and Send as permission to Exchange 2007 Mailbox

Below powershell can help to apply users full access rights and and SendAs permission to the mailbox for the given input CSV file

Format ofthe CSV something like this

UserMailbox,User
Krishna,Domain/Krishna

———————————————————————————————————————-

$csv = Import-csv -path “C:\Userdetails.csv”
foreach($line in $csv)
{
Add-MailboxPermission $Line.UserMailbox -AccessRights FullAccess -user $Line.User
Add-ADPermission $Line.UserMailbox -Extendedrights “Send As” -User $Line.User

}

———————————————————————————————————————-

Powershell to get the list of user who last logon time is older then 30 days

Below is the powershell command to get the list of mailbox who last log time is older then 30 days. This would be very help ful when you wanted to try to clean up exchagne server from unused account.  You can change from 30 to 6o or 90 days based on the requirement.

Get-MailboxStatistics | where {$_.Lastlogontime -lt (get-date).AddDays(-30)} | Select displayName,LastLoggedOnUserAccount,LastLogonTime

Script to check if Active Directory User Account is Active or Disabled throught Powershell

Below powershell helps to get if a give account is active or disabled, We can loop it for the given list of users

$K = “Krishna.k”
$adobjroot = [adsi]”
$objdisabsearcher = New-Object System.DirectoryServices.DirectorySearcher($adobjroot)
$objdisabsearcher.filter = “(&(objectCategory=user)(objectClass=user)(sAMAccountName= $K)(userAccountControl:1.2.840.113556.1.4.803:=2))”
$resultdisabaccn = $objdisabsearcher.findone()

if($resultdisabaccn)
{
 Write-Output “ACcount is Disabled”
}
 Else
{
 Write-Output “ACcount is Active”
}

Powershell to get Complete Mailbox Statistics in the Exchange 2007 Orginisation

 

Below is the powershell command to export the complete details of the Mailbox in the Exchange Organization. Details like Name, Mailbox size (MB), Mailcount, Mailbox limits, Account Active or disabled, CreatedDate, Lastlogon time, Last logofftime etc into the CSV file. This Data can even imported in to the SQL database and Query to analyst the growth of the mailbox. If you collect these details on Daily basis and uploaded into SQL then you can easily get the details of the mailbox in seconds for auditing or capacity management etc.

With SQL integration you can query details like Top 100 mailbox, Top 100 Fastest growing mailbox, List of all active maibox, List of disabled mailbox, List of mailbox out of default quota limits, maiboxes not used in past few days. Newly created mailbox in past one month etc

Get-Mailbox -ResultSize Unlimited |  select DisplayName, Alias, Database, PrimarySmtpAddress,@{name=’IssuewarningQuota’;expression={if ($_.IssueWarningQuota -match “UNLIMITED”) {“-1”} else {$_.IssueWarningQuota.value.tomb() }}},@{name=’ProhibitSendQuota’;expression={if ($_.ProhibitSendQuota -match “UNLIMITED”) {“-1”} else {$_.ProhibitSendQuota.value.tomb() }}},@{name=’ProhibitSendReceiveQuota’;expression={if ($_.ProhibitSendReceiveQuota -match “UNLIMITED”) {“-1”} else {$_.ProhibitSendReceiveQuota.value.tomb() }}},WhenCreated  |export-csv C:\stats.csv
“DisplayName,Alias,MailboxSizeMB,ItemCount,PrimarysmtpAddress,IssueWarningQuotaMB,ProhibitSendQuotaMB,ProhibitSendReceiveQuotaMB,DatabaseName,CreationDate,LastLogonTime,LastLogoffTime,isActive” | out-file C:\MailstatsResult.csv
$csv = Import-csv -path “C:\stats.csv”
foreach($line in $csv)
{
 $MailboxStats =  Get-MailboxStatistics $Line.Alias | Select TotalItemSize,Itemcount,LastLogoffTime,LastLogonTime
 $L = “{0:N0}” -f $mailboxstats.totalitemsize.value.toMB()
 $Size = “”
 $Len = $L.Split(‘,’)
 for ($i=0; $i -lt $Len.length; $i++)
  {
   $Size = $Size +$Len[$i]
  }
  $temp=$Line.PrimarysmtpAddress
  $adobjroot = [adsi]”
  $objdisabsearcher = New-Object System.DirectoryServices.DirectorySearcher($adobjroot)
  $objdisabsearcher.filter = “(&(objectCategory=Person)(objectClass=user)(mail= $Temp)(userAccountControl:1.2.840.113556.1.4.803:=2))”
  $resultdisabaccn = $objdisabsearcher.findone() | select path

if($resultdisabaccn.path)
 {
 $actStatus = “1”
 }
 Else
 {
 $actStatus = “0”
 }
 
 $out =$Line.Displayname  + “,” + $Line.Alias  + “,” +  $Size + “,” + $MailboxStats.ItemCount  + “,” + $Line.PrimarySmtpAddress   + “,” +  $Line.IssueWarningQuota + “,” +  $Line.ProhibitSendQuota  + “,” +  $Line.ProhibitSendReceiveQuota + “,” + $Line.Database + “,” +  $Line.WhenCreated + “,” + $MailboxStats.LastLogonTime + “,” + $MailboxStats.LastLogoffTime + “,” + $actStatus
 $Out | Out-File C:\MailstatsResult.csv -Append
}

You can get the copy of the script in the below text file

http://powershell.com/cs/cfs-filesystemfile.ashx/__key/CommunityServer.Components.UserFiles/00.00.00.30.62/MailboxStats.txt

Powershell to Get HomeDirectory details for the given list of users

 

Below code helps to get the list of HomeDirectory Path for the given list of users in the text file as input

$UserList = Get-Content “c:\users.txt”
$domain = [ADSI]””
foreach($UserName in $UserList)
{ $searcher = new-object DirectoryServices.DirectorySearcher($domain)
$searcher.filter = “(&(objectClass=user)(sAMAccountName= $UserName))”
$SearchResult = $searcher.findall() | select Properties
$Homepath = $username + ” –  ” + $SearchResult.properties.homedirectory
$Homepath
}

Working with Recovery Storage Group in Exchange 2007 using powershell and Microsoft Exchange Troubleshooting Assiatance

 

Recovery Storage group is the feature of restoring and mount the second copy of the exchange mailbox store to the exchange server to export mails and data from the required mailboxes with out affecting the production. This is originally introduced in Exchange 2003 SP1.

 

Features

  1. Only one Recovery storage group can be created in a exchange server
  2. Recovering database and Exchange 2007 server should be on the same active directory forest.
  3. Recovery Storage group can be managed in two ways one with Microsoft Exchange troubleshooting assistant(ExTRA) and Exchange power shell    

Below article describes procedure steps to work on Recovery Storage group using power shell

1. Below snap of DB3 which we will be working on recovering in to the Recovery Storage Group

 

 

 

2. Lets take the backup of DB3 using default windows Backup Utility

 

 

 

 

3. Create a new Recovery Storage group using Exchange powershell, below is the command for the same. –Recovery option will create a recovery storage group.

New-StorageGroup –Server <servername>  –LogFolderPath “D:\Recovery Storage Group\log” –Name “Recovery Storage Group” –SystemFolderPath “D:\Recovery Storage Group\log” –Recovery

 

4. Get-StorageGroup “Recovery storage group” | fl
   Will get the details of the new Recovery storage group which is created now

5. Create the new Database with the name DB3 and provide the path of the Edb file. 
  

5. Create the new Database with the name DB3 and provide the path of the Edb file.
   New-MailboxDatabase –MailboxDatabaseToRecover “DB3” –StorageGroup “Servername\Recovery Storage Group” –EDBFilePath “D:\Recovery Storage Group\DB\DB3.edb”

6. Once Mailbox Database is created we need to restore from the backup before that the restore we need set AllowFilerestore to true with the below command
    Set-MailboxDatabase -Identity “<ServerName>\Recovery Storage Group\DB3” -AllowFileRestore $true

7. Use Backup Utility to restore the Database to the Recovery Storage group. By selecting the DB3 and click restore and make sure that “Last Restore Set” is checked

 

 

 

 

 

 

 

 

 

 

 

 

8. Mount the Restored database using below mentioned power shell command
   Mount-Database –Identity “<SERVERNAME>\Recovery Storage Group\DB3”

9. Final step is merging mails from the Recovery Storage group mails to production mailbox. This can be done either both from ExTRA (Exchange Trouble shooting assistance) and from Power shell. I feel that recovering mail using Extra is much easier then recovering through power shell. Power shell will not only merge on the production mailbox into the folder name Recovered but ExTRA will directly merge into the production mailbox.  

10. To open ExTRA, Open Exchange Management console and click on tools and on the right panel click on Database Recovery Management.

 

 

 

11. Click on “Select Task” on the left column on ExTRA and click on Database recovery Management and  In the next page enter the Mailbox Server name and DC and click on  Next to continue to get the below mentioned page and click on Merge or copy mailbox content

 

 

 

 

 

 

 

 

 

 

 

 

12. Click on “Gather merge information”

 

 

 

 

13. Select the required mailbox and click on “Perform merge action” to merge the recovered mailbox to the production mailbox. Recovered mail will directly reflect in the mailbox of the user