SMTP Port 25

Anything and Everything Related to Messaging and Collaboration, Active Directory and Scripting. It’s My Life!!!

Archive for the ‘Powershell’ Category

Windows PowerShell 3.0

Posted by Krishna - MVP on September 7, 2012

Windows PowerShell 3.0 is next big thing in the IT world. It has got lots of interesting stuff. I have outlined some of the good features in the below articles

Powershell 3.0 Overview – Part 1

Powershell 3.0 Overview – Part 2

Hope you like these articles Smile

Posted in Powershell, Windows 2012 | Tagged: , , , | Leave a Comment »

Exchange 2010 SP1/SP2 – Deleting email sent to Wrong DL

Posted by Krishna - MVP on January 27, 2012

As an Exchange Admin, how many times have you got a request to delete email, from your senior management, for deleting specific emails from specific mailboxes? I am sure most of you would say, ”Its Crazy Man”. I personally have seen very important emails being sent to a wrong DL and management coming to us for help. Users may even try to recall the message, with only some being successful. This would add a new set of emails in the mailbox. There can also be situations like, where Spam emails are sent to the DL users’ mailbox, or there is a requirement to delete emails between specific dates. These are the various possible requirements from users, and it does not come as a surprise to me.

In Exchange 2000 and 2003, this can be achieved by using Exmerge.

In Exchange 2007, this can be achieved by using export-mailbox and this cmdlet has enhanced in Exchange 2010 to New-MailboxExportrequest. The cmdlet does not comes with the option to delete the contents. MS also have added couple new cmdlets to export and import the content of the mailbox

In Exchange 2010, this can be achieved using search-Mailbox

Here are simple steps for the Exchange Admins, who can get this task done real quick in Exchange 2010 SP1/SP2 using search-mailbox. But, keep in mind that, these steps suggest permanent deletion, which removes emails from dumpster as well. So only option to recover is go back to backup.

  1. In Exchange 2010, if you want to Import and Export mailbox content and delete unwanted email from the mailbox then, you need to have Mailbox Import Export management role assigned.
  2. Below Powershell cmdlet, New-ManagmentRoleAssignment helps us to assign the right management role “mailbox Import Export” to a particular user.
New-managementRoleAssignment –Role “Mailbox Import Export” –User administrator

clip_image002

Figure 1.  Assigning a new Management role for a user Administrator

3. Similarly if you want to have the permission assigned to a group of users, then you can use the below cmdlet. Make sure you assign the permission to the universal security group.

New-ManagementRoleAssignment -Name "Import-Export Admins" -SecurityGroup "Security group name" -Role "Mailbox Import Export"

4. Once you have the necessary permission to run the search-mailbox then, we are good to start. Lets start with search and on logging mode, so that we have the search result logged in the target mailbox

5.  Below is the Powershell cmdlet search-mailbox, which goes through each mailbox in distribution group OrgVIP, in log only mode. It will generate the report on the log, in the Target mailbox temp, under the folder the Search result. Figure 2. shows the details of the execution.

get-DistributiongroupMember Orgvip | Search-Mailbox -SearchQuery subject:"Organization Financial Report" -TargetMailbox Temp -TargetFolder SearchResult -LogLevel Full

clip_image004

Figure 2. Execution details of the Search-mailbox cmdlet with logonly mode

6. With loglevel Full option the cmdlet will generate the CSV in the target mailbox. Figure 3. shows the details of the CSV result file.

clip_image006

Figure 3. Details after execution of search-mailbox in log only mode.

6. It’s always recommended to have a copy of these emails, which are being searched for, as a back-up reference. To get a copy of all the reference email, just remove the -logonly option

get-DistributiongroupMember Orgvip | Search-Mailbox -SearchQuery subject:"Organization Financial Report" -TargetMailbox Temp -TargetFolder SearchResult -LogLevel Full

7. Figure 4. Shows the details of the searched emails in the target mailbox. It has the copy of the emails with the detail location. If an email is deleted/moved, it will show the current location folder, and if it is moved to the dumpster, then the result would also show the dumpster folder details.

clip_image008

Figure 4. Copy the searched email to the target mailbox.

8. Finally we have the copy of the emails. Now, It is time to delete the emails. Below is the Powershell cmdlet, which searches each mailbox from the DL and deletes the contents. To delete the content we need to use the option Deletecontent. You really don’t have to provide the target mailbox parameter for deleting the emails.

get-DistributiongroupMember Orgvip | Search-Mailbox -SearchQuery subject:"Organization Financial Report" -DeleteContent

9. The search query is the important attribute of the cmdlet. It can be passed with various options, to get more accurate search results. TechNet Reference

Property Example
Attachments attachment:annualreport.pptx
Cc cc:paul shencc:paulscc:pauls@contoso.com
From from:bharat sunejafrom:bsunejafrom:bsuneja@contoso.com
Sent sent:yesterday
Subject Subject:”patent filing”
To to:”ben Smith” “to:bsmithto:besmith@contoso.com”
Body Financial Report

10. Couples of various situation to use search-mailbox with delete content

A. Searching and deleting email containing attachment spam.csv in all the mailbox in the organization

get-mailbox -resultsize unlimited | Search-Mailbox -SearchQuery attachment:"spam.csv" -DeleteContent

D. Searching and deleting emails containing attachment spam.csv and subject is hi against all the mailbox in the organization

get-mailbox -resultsize unlimited | Search-Mailbox -SearchQuery 'attachment:"spam.csv" and subject:Hi' -DeleteContent

C. If you wanted to display the details of the search result on the shell then you need to use the option Estimateresultonly

get-mailbox -server <Servername> | Search-Mailbox -SearchQuery 'attachment:"spam.csv" and subject:Hi' -Estimateresultonly

D. Delete all the email from all the mailbox of a before the specific date. In the below example I am deleting all the email before the date 18th Sep 2011(“dd/mm/yyy’)

get-mailbox -database <Databasename> -resultsize unlimited | Search-Mailbox -SearchQuery Received:<$("09/18/201") -deletecontent

E. Delete all the email from all the mailbox of a database between the specific dates. In the below example I am deleting all the email before the date 18th Sep 2011(“dd/mm/yyy’) – 1st Jan 2012

get-mailbox -database <Databasename> -resultsize unlimited | Search-Mailbox -SearchQuery Received:<$("09/18/2011") –deletecontent

F. Delete all the email from the mailbox between the specific date

Search-Mailbox -Identity <mailboxname> -SearchQuery 'Received:>$("09/18/2011") and Received:<$("01/27/2012")` -deletecontent

G. Delete all the email from yesterday against the member of the distribution group.

get-DistributiongroupMember Orgvip | Search-Mailbox -SearchQuery Received:today -deletecontent -confirm:false   

H. Delete all the email on a specific date from a specific mailbox.

Search-Mailbox <usermailbox> -SearchQuery Received:01/27/2012 -deletecontent

Search-mailbox is a cool and nice cmdlet with some good options to get the required result. I think this is make life of the exchange administrator easier on a tough situations. Hope this helps you to face a real time scenarios Winking smile

Posted in Exchange 2010, Powershell | Tagged: , , , | 2 Comments »

Exchange 2010 – Reseeding failed Database with multithreading

Posted by Krishna - MVP on September 23, 2011

Reseeding is a process of fixing the failed passive copy of the database which basically mean is, the passive database copy is out of sync with active database. Passive copies can be a failed database or failed Index. When Database goes in failed state or failed and suspended state or database Index goes in to failed state then it needs administrator intervension and force the database reseed.  

There can be various reason for database to fail. Replication service running on the host machine is responsible for keeping the database in healthy state. It tries to take corrective action if the database goes out of sync else administrator may have to fix failed database manually.

Below is the nice piece of code which will request you to enter the DAG Name and it will determine the list of failed database and perform full reseed on each of the failed database. In the normal process, reseeding happends on the single database at a time and you can’t limit how many database you can reseed at a time. Eg

Get-MailboxDatabaseCopyStatus $strResponse  |?{$_.status -like “Failed*”} | update-mailboxdatabasecopystatus -deleteexistingfiles -confirm:$false

In the above example cmdlet will get all the failed database and it pipes to update-mailboxdatabase cmdlet. Update-Mailboxdatabasecopy performs the full reseed of the failed database one by one and brings the database into healthy state. If we have very bigger database like 100 GB and it has to update to different site then you know how long it may take. With this senarion you dont want to fix one failed database at a time.

Below script helps you to address the above defined issue. It can reseed the failed database up to max of 10 database in 10 different window at a time and if one database reseeding completes then new failed database will reseed if there is any. This count can be reduced or increased based on the performance of the local server and the network available.

function Createfolders()
{
 remove-item -path "C:\DBs\bt" -force  -Recurse -confirm:$false -ErrorAction SilentlyContinue | out-null
 remove-item -path "C:\DBs\ps" -force  -Recurse -confirm:$false -ErrorAction SilentlyContinue| out-null
 remove-item -path "C:\DBs" -force  -Recurse -confirm:$false -ErrorAction SilentlyContinue| out-null

 new-item -path "C:\DBs" -ItemType Directory -force | out-null
 new-item -path "C:\DBs\bt" -ItemType Directory -force | out-null
 new-item -path "C:\DBs\ps" -ItemType Directory -force | out-null
}
$strResponse = Read-Host  "`nPlease enter DAG Name to reseed the failed Databases"

write-host -f Magenta "Checking for Failed Database copies in the DAG : $strResponse"

$databases = Get-MailboxDatabaseCopyStatus $strResponse  |?{$_.status -like "Failed*"}
if($databases -ne $null)
{
 write-host -f red "Following Databases are in failed state"
 $databases
 Write-host "`n"
 foreach($database in $databases)
 {
 $filename = $database.name
 $dbname = $database.name

 $filename = $filename.Replace("\", "_")
 $DBcopyReport1 = "C:\DBs\bt\$filename.bat"
 $DBcopyReport2 = "C:\DBs\ps\$filename.ps1"
 New-item -ItemType file -path $DBcopyReport1 -force | out-null
 New-item -ItemType file -path $DBcopyReport2 -force | out-null

 "Powershell.exe `"C:\DBs\bt\$filename.ps1`"" |  Out-File -filepath $DBcopyReport1 -encoding ASCII -append
 "Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 -ErrorAction SilentlyContinue"| Out-file $DBcopyReport2 -encoding ASCII -append
 "Suspend-MailboxDatabaseCopy -Identity `"$dbname`" -confirm:" + "$" + "false"| Out-file $DBcopyReport2 -encoding ASCII -append
 "Update-MailboxDatabaseCopy -Identity `"$dbname`"  -DeleteExistingFiles -confirm:" + "$" + "false -ErrorAction:Stop -WarningAction:SilentlyContinue" | Out-file $DBcopyReport2 -encoding ASCII -append

&nbsp;

 $files = [IO.Directory]::GetFiles("C:\DBs\bt\")
 $cmdprocess = @()
 Write-host -f yellow "`nReseeding the following databases"
 for ($i=0; $i -lt $files.count; $i++)
 {
  $DBDName = $files[$i]
  $DBDName =$DBDName.split("\")[3]
  $DBDName =$DBDName.split(".")[0]
  $DBDName = $DBDName.Replace("_","\")
  Write-host -f yellow "$DBDName"
  $cmdprocess =$cmdprocess+ [diagnostics.process]::Start($files[$i])
  do
  { 
   $cmdp = @()
   $continue = 0
   foreach($cmdproces in $cmdprocess)
   {
    $cmdp = $cmdp + $cmdproces.id
   }
   $processid = Get-Process | %{$_.id}
   foreach($cmd in $cmdp)
   {
    if($processid -contains $cmd)
    {  
     $continue = $continue + 1
    }
   }
   start-sleep(10)
 
  }until($continue -lt 10)

 }
 do
 {
  $processid = Get-Process | %{$_.id}
  $Loopexit = 0
  foreach($cmd in $cmdp)
  { 
   if($processid -contains $cmd)
   {
   $Loopexit = 1
   start-sleep(10)
   }
  }
 }
 until($Loopexit -eq 0)

 Write-host -f Green "`nReseeding of Failed DB's has been completed"
}
Else
{
 Write-host -f Green "All the mailbox Database copy are in Healthy state"
}

Createfolders
Write-host -f Magenta "`nChecking for failed Catalog or Content Index in the DAG :$strResponse"
$databases = Get-MailboxDatabaseCopyStatus $strResponse  |?{$_.ContentIndexState -match "Fail" }
if($databases -ne $null)
{
write-host -f red "Following Databases are in failed state"
 $databases
 Write-host "`n"
 foreach($database in $databases)
 {
 $filename = $database.name
 $dbname = $database.name

 $filename = $filename.Replace("\", "_")
 $DBcopyReport1 = "C:\DBs\bt\$filename.bat"
 $DBcopyReport2 = "C:\DBs\ps\$filename.ps1"
 New-item -ItemType file -path $DBcopyReport1 -force | out-null
 New-item -ItemType file -path $DBcopyReport2 -force | out-null

 "Powershell.exe `"C:\DBs\bt\$filename.ps1`"" |  Out-File -filepath $DBcopyReport1 -encoding ASCII -append
 "Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 -ErrorAction SilentlyContinue"| Out-file $DBcopyReport2 -encoding ASCII -append
 "Suspend-MailboxDatabaseCopy -Identity `"$dbname`" -confirm:" + "$" + "false"| Out-file $DBcopyReport2 -encoding ASCII -append
 "Update-MailboxDatabaseCopy -Identity `"$dbname`"  -DeleteExistingFiles -confirm:" + "$" + "false -ErrorAction:Stop -WarningAction:SilentlyContinue" | Out-file $DBcopyReport2 -encoding ASCII -append

&nbsp;

 $files = [IO.Directory]::GetFiles("C:\DBs\bt\")
 $cmdprocess = @()
 Write-host -f yellow "`nReseeding the following databases"
 for ($i=0; $i -lt $files.count; $i++)
 {
  $DBDName = $files[$i]
  $DBDName =$DBDName.split("\")[3]
  $DBDName =$DBDName.split(".")[0]
  $DBDName = $DBDName.Replace("_","\")
  Write-host -f yellow "$DBDName"
  $cmdprocess =$cmdprocess+ [diagnostics.process]::Start($files[$i])
  do
  { 
   $cmdp = @()
   $continue = 0
   foreach($cmdproces in $cmdprocess)
   {
    $cmdp = $cmdp + $cmdproces.id
   }
   $processid = Get-Process | %{$_.id}
   foreach($cmd in $cmdp)
   {
    if($processid -contains $cmd)
    {  
     $continue = $continue + 1
    }
   }
   start-sleep(10)
 
  }until($continue -lt 10)

 }
 do
 {
  $processid = Get-Process | %{$_.id}
  $Loopexit = 0
  foreach($cmd in $cmdp)
  { 
   if($processid -contains $cmd)
   {
   $Loopexit = 1
   start-sleep(10)
   }
  }
 }
 until($Loopexit -eq 0)

 Write-host -f Green "`nReseeding of Failed DB's has been completed"
}
Else
{
 Write-host -f Green "All the mailbox Database copy Index are in Healthy state"
}

Below is the snap of the execution window and we can see how DB reseed is been executed on multiple window. This will save you lot of time and effors in fixing the database. I hope this article will be helpful to you :)

Posted in Exchange 2007, Exchange 2010, Powershell | Tagged: , , , | 1 Comment »

Enable and Disabling Circular logging on Exchange 2010 DAG Database on a fly.

Posted by Krishna - MVP on September 1, 2011

In Exchange 2007 and earlier version of Exchange if you wanted to enable or disable circular logging then you should dismount and mount the database to bring this into effect. In Exchange 2010 if you enable or disable circular logging then this chance will come into effect with in 30 seconds. This is done with the help of replication service and you dont have to dismount and mount the active database to get this changes applied. I think this is cool. You can make the changes on the fly without disrupting the mailbox live users.

Enable circular logging on a Particular database

Get-mailboxdatabase -Identity DBname | set-mailboxdatabase -CircularloggingEnabled $true

Disable circular logging on a Particular database

Get-mailboxdatabase -Identity DBname | set-mailboxdatabase -CircularloggingEnabled $false

Enable Circular logging on all the Database in a perticular DAG

Get-mailboxdatabase -identity DAGname* | set-mailboxdatabase -CircularloggingEnabled $true

Disable Circular logging on all the database in a perticular DAG

Get-mailboxdatabase -identity DAGname* | set-mailboxdatabase -CircularloggingEnabled $false

Feeling nice to blog after a long time on a auspecious day :)

Posted in Exchange 2010, Powershell | Tagged: , , , | 1 Comment »

Configure ANONYMOUS Relay on Exchange 2007/10 Receive connectors

Posted by Krishna - MVP on February 10, 2011

When every any new Exchange 2007/2011 Hub role is installed, by default 2 receive connectors will be created and they are

 Default <Server name>: Works on port 587

Client <Server name>: Works on port 25

 These connectors are configured to receive messages from the Internet, from e-mail clients, and from other e-mail servers. These Hub servers are not configured for Authenticated relay. If your hub servers are configured to receive email from the Internet or from other email servers which cannot perform authentication then you may have to configure to allow Anonymous relay on the receive connectors

 Below cmdlet helps to configure email from any anonymous recipient

 Get-ReceiveConnector “Receive Connector Name” | Add-ADPermission -User “NT AUTHORITY\ANONYMOUS LOGON” -ExtendedRights “Ms-Exch-SMTP-Accept-Any-Recipient

Posted in Exchange 2007, Exchange 2010, Powershell | Tagged: , , | 2 Comments »

Playing with Network Card properties using nvspbind

Posted by Krishna - MVP on February 6, 2011

If any one had asked me a question  to Disable a File and Print Sharing from Microsoft network using a script or a command one year before, i would have simply said I don’t know. But now, my answer would be ok!!

nvspbind is the new tool written for Windows 2008 Hyper V Servers. Its magical tool and can be used for all Windows 2008 Class servers. nvpsbind helps to enable and disable various network settings like Client for Microsoft network,Qos Packet Scheduler, File and Printer sharing for Microsoft network and the rest. It even allows to configure network binding order. If you windows server is configured as cluster and one of the mandatory requirement is to have 2 or more nic cards and it has to be configured correctly and binding order has to be configured right. Public network in the cluster should be on top of the binding order and followed by replication network.

These things can be done manually as well, but why do i have to use this tool ? Simple, If you wanted to do this on one server, i dont recommend this. But if you wanted to configure on 10 servers may be 100 then i  would recommed.

You can find  copy of the file here..http://code.msdn.microsoft.com/nvspbind/Release/ProjectReleases.aspx?ReleaseId=3837

Below are some nvspbind examples to enable and disable specific network settings

nvspbind -d “Nic Name” ms_tcpip6 (To uncheck IPV 6 on a Specific Network)
nvspbind -e “Nic Name” ms_tcpip6 (To check IPV 6 on a Specific Network)
nvspbind -d “Nic Name” ms_server (To uncheck File and Printer Sharing for Microsoft Networks)
nvspbind -e “Nic Name” ms_server (To check File and Printer Sharing for Microsoft Networks)

Below are some nvspbind examples to Brint specific network binding order on top of the list.

nvspbind /++ “Nic Name ” ms_tcpip
nvspbind /– “Nic Name ” ms_tcpip

This tool is for all people in the world who wanted to make there life easy with automation and automation is my spirit of life :)

Posted in Powershell, Windows 2008 | Tagged: , , , , , , | Leave a Comment »

Powershell to get the complete Exchange Database Name,Edb filepath and log file path into a Single file Report

Posted by Krishna - MVP on January 11, 2011

Powershell to get the complete Exchange Database Name,Edb filepath and log file path into a Single file Report

$exchangeservers = Get-ExchangeServer |where-object {$_.admindisplayversion.major -eq 8 -and $_.IsMailboxServer -eq $true }
$result = "Servername | Database Name | EDB file Path | Log files Path"
$result > DBresultfile.txt
foreach ($server in $exchangeservers)
{
 $db = Get-MailboxDatabase -server $server
 $servername = $server.name
 foreach ($objItem in $db)
  {
  $result = $servername + " | " + $objItem.Name  + " | " + ($objItem.EdbFilePath).pathname + " | " + ((Get-StorageGroup $objItem.StorageGroup | select LogFolderPath).LogFolderPath).pathname
  $result
  $result >> DBresultfile.txt
  }
}

Posted in Exchange 2007, Powershell | Tagged: , , , , | 2 Comments »

PowerShell to Configure not to prompt open file security Warning

Posted by Krishna - MVP on December 19, 2010

Exchange 2010 Automation Tip 2

PowerShell is automation when I ever I say this I feel that I have the Power in me and that’s automation power… Whenever you try double clicking on exe you will prompted for the open file security warning. This does happen when you try to do the same using PowerShell cmdlets. When you trying to automate this on 100 are of server then you need to find some solution. Here is one from me. You need to add the required files into the registry as low risk files. Same can be configured using local Group policy. When configure the GPO, it also edit the values into the registry J . Below PowerShell can use us to add and remove the low risk registry files    

$Lowriskregpath ="HKCU:\Software\Microsoft\Windows\Currentversion\Policies\Associations"
$Lowriskregfile = "LowRiskFileTypes"
$LowRiskFileTypes = ".exe,.msp"
Function Addlowriskfiles()
    {
    New-Item -Path $Lowriskregpath -erroraction silentlycontinue |out-null
    New-ItemProperty $Lowriskregpath -name $Lowriskregfile -value $LowRiskFileTypes -propertyType String -erroraction silentlycontinue |out-null
    }
Function removelowriskfiles()
    {
    remove-itemproperty -path $Lowriskregpath -name $Lowriskregfile -erroraction silentlycontinue
    }

Low risk files you are very important…!!!

Posted in Exchange 2007, Powershell | Tagged: , , , , , | Leave a Comment »

Powershell Folder Permssion

Posted by Krishna - MVP on December 2, 2010

Here is a nice article on Configuring permssion using powershell cmdlet

http://blogs.technet.com/b/josebda/archive/2010/11/12/how-to-handle-ntfs-folder-permissions-security-descriptors-and-acls-in-powershell.aspx

Posted in Powershell | Tagged: , | Leave a Comment »

Exchange 2007 – Activation of DR Site and Failback to primary

Posted by Krishna - MVP on November 26, 2010

Exchange 2007 – Activation of DR Site and Failback to primary – Quick Reference..

http://technet.microsoft.com/en-us/library/bb738150(EXCHG.80).aspx

http://messaging24x7.wordpress.com/2010/08/04/exchange-server-2007-ccr-with-standby-continuous-replication-target-disaster-recovery/

Posted in Exchange 2007, Powershell | Tagged: , , | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.

Join 49 other followers