Solved

Script Help Exchang 2010 Search-mailbox command

Posted on 2015-02-02
26
286 Views
Last Modified: 2015-03-02
Exchange 2010 Enterprise 64 bit



Wrote a script to export my journal inbox to a pst file one a week.

******************************************************************************************************

$today = Get-Date -Format "MMddyyyy"
$Folder = "\\10.2.8.20\volume_1\email\journal\journal-$today"
[System.Reflection.Assembly]::LoadWithPartialName("System.Threading")
[System.Reflection.Assembly]::LoadWithPartialName("System.Globalization")
[System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo]::CreateSpecificCulture("en-us")

add-pssnapin Microsoft.*

$start = (get-date).adddays(-7)
$end = (get-date)
$filter = "(Received -gt '"+$start+"') -and (Received -lt '"+$end+"')"
New-MailboxExportRequest –Mailbox journal -FilePath "$folder.pst" -ContentFilter "$filter" -confirm:$false -verbose -baditemlimit 1 >>c:\util\journal.txt

Get-MailboxExportRequest | where {$_.status -eq "Completed"} >>c:\util\journal.txt

search-mailbox -identity 'exchange journal' -searchquery "Received:'"+$start+"'..'"+$end+"'"  -deletecontent >>c:\util\journal.txt -force

******************************************************************************************************


My problem is that the search-mailbox command never executed.

I am guessing that the New-mailboxexportrequest   was queued up


How can I test for that before the search-mailbox command runs?
0
Comment
Question by:Thomas Grassi
  • 14
  • 11
26 Comments
 
LVL 3

Expert Comment

by:Rezwan Islam
ID: 40585264
Variable inside the quotes could be stopping it from running. Try without any variable may be to ensure the cmdlet runs first,

search-mailbox -identity 'exchange journal' -targetmailbox "AdminSearchMailbox" -targetfolder "Search Output"-searchquery {received:mm/dd/yyyy..mm/dd/yyyy}

then you can use the -deletecontent switch. I think the date out format from your $start and $end variable were not going to be accepted anyway.
0
 
LVL 23

Author Comment

by:Thomas Grassi
ID: 40585271
Rezwan

I ran it manually after the script failed and also during my testing

search-mailbox -identity 'exchange journal' -searchquery "Received:01/25/2015..02/02/2015"  -deletecontent >>c:\util\journal.txt -force

This runs and works.

I want to make sure the New-MailboxExportRequest commands finishes first before I run this command


Thoughts
0
 
LVL 3

Expert Comment

by:Rezwan Islam
ID: 40585323
May be something like this will work mate,

$Completed = Get-MailboxExportRequest -mailbox journal | Where {$_.Status -eq “Completed”}

if ($Completed) {
          search-mailbox ....
}
0
 
LVL 23

Author Comment

by:Thomas Grassi
ID: 40585328
Rezwen

Thanks

Will give that a try

What will happen if the status is queued?

Can we loop this ? maybe loop for every 1 min for up to 10 mins?  something like that is that possible?
0
 
LVL 3

Expert Comment

by:Rezwan Islam
ID: 40585336
You are full of ideas !

may be try something like this,

$Completed = Get-MailboxExportRequest -mailbox journal | Where {$_.Status -eq “Completed”}

$timeout = new-timespan -Minutes 10
$ticker = [diagnostics.stopwatch]::StartNew()

while ($ticker.elapsed -lt $timeout) {    
      if ($Completed) {      
             search-mailbox ..        
             return        
       }    
      start-sleep -seconds 60
}

you will probably have to tweak a little bit here and there. I never tried to loop a command before. Only looped scripts. Hope this helps.
0
 
LVL 23

Author Comment

by:Thomas Grassi
ID: 40587269
Rezwan
 
This is what I came up with.

My question is We need to rerun the
$Completed = Get-MailboxExportRequest -mailbox journal | Where {$_.Status -eq “Completed”} >>c:\util\journal.txt

at each pass until the status shows "completed"

Am I missing a "TAG"  ?


$today = Get-Date -Format "MMddyyyy"
$Folder = "\\10.2.8.20\volume_1\email\journal\journal-$today"
[System.Reflection.Assembly]::LoadWithPartialName("System.Threading")
[System.Reflection.Assembly]::LoadWithPartialName("System.Globalization")
[System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo]::CreateSpecificCulture("en-us")

add-pssnapin Microsoft.*

$start = (get-date).adddays(-7)
$end = (get-date)
$filter = "(Received -gt '"+$start+"') -and (Received -lt '"+$end+"')"

New-MailboxExportRequest –Mailbox journal -FilePath "$folder.pst" -ContentFilter "$filter" -confirm:$false -verbose -baditemlimit 1 >>c:\util\journal.txt

$Completed = Get-MailboxExportRequest -mailbox journal | Where {$_.Status -eq “Completed”} >>c:\util\journal.txt

 $timeout = new-timespan -Minutes 10
 $ticker = [diagnostics.stopwatch]::StartNew()

 while ($ticker.elapsed -lt $timeout) {    
       if ($Completed) {       
              search-mailbox -identity 'exchange journal' -searchquery "Received:'"+$start+"'..'"+$end+"'"  -deletecontent >>c:\util\journal.txt -force       
              return        
        }     
       start-sleep -seconds 60
 }

Open in new window



Thanks
0
 
LVL 3

Expert Comment

by:Rezwan Islam
ID: 40587676
Sorry my bad, please try to put
$Completed = Get-MailboxExportRequest -mailbox journal | Where {$_.Status -eq “Completed”} >>c:\util\journal.txt

between while and If statement lines and see if that works for you.
0
 
LVL 23

Author Comment

by:Thomas Grassi
ID: 40587685
Rezwan


Thanks will do.
0
 
LVL 23

Author Comment

by:Thomas Grassi
ID: 40599576
Rezwan



It ran 10 times I see in the report the output from the
 $Completed = Get-MailboxExportRequest -mailbox journal | Where {$_.Status -eq “Completed”} >>c:\util\journal.txt
worked.

But the

if ($Completed) {      
              search-mailbox -identity 'exchange journal' -searchquery "Received:'"+$start+"'..'"+$end+"'"  -deletecontent >>c:\util\journal.txt -force      
              return        
        }    

the search-mailbox command did not run or work

I ran it manually just to keep the inbox clear.

Wondering if this "Received:'"+$start+"'..'"+$end+"'"   is not being converted to this "Received:02/02/2015..02/09/2015"

Thoughts?

My Current script.


$today = Get-Date -Format "MMddyyyy"
$Folder = "\\10.2.8.20\volume_1\email\journal\journal-$today"
[System.Reflection.Assembly]::LoadWithPartialName("System.Threading")
[System.Reflection.Assembly]::LoadWithPartialName("System.Globalization")
[System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo]::CreateSpecificCulture("en-us")

add-pssnapin Microsoft.*

$start = (get-date).adddays(-7)
$end = (get-date)
$filter = "(Received -gt '"+$start+"') -and (Received -lt '"+$end+"')"

New-MailboxExportRequest –Mailbox journal -FilePath "$folder.pst" -ContentFilter "$filter" -confirm:$false -verbose -baditemlimit 1 >>c:\utiljournal.txt


$timeout = new-timespan -Minutes 10
$ticker = [diagnostics.stopwatch]::StartNew()

while ($ticker.elapsed -lt $timeout) {    
    $Completed = Get-MailboxExportRequest -mailbox journal | Where {$_.Status -eq “Completed”} >>c:\util\journal.txt
       if ($Completed) {       
              search-mailbox -identity 'exchange journal' -searchquery "Received:'"+$start+"'..'"+$end+"'"  -deletecontent >>c:\util\journal.txt -force       
              return        
        }     
       start-sleep -seconds 60
 }

Open in new window

0
 
LVL 3

Expert Comment

by:Rezwan Islam
ID: 40602505
Sorry about the delay. I think you are very close.

I have modified your script a little and have tested this in my test lab. It worked for me, see if you can make it work. Here is the full script. Had to try and fit in your start and end variables inside the received parameter.

#===================start-of-script=======================

$today = Get-Date -Format "MMddyyyy"
$Folder = "\\10.2.8.20\volume_1\email\journal\journal-$today"
[System.Reflection.Assembly]::LoadWithPartialName("System.Threading")
[System.Reflection.Assembly]::LoadWithPartialName("System.Globalization")
[System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo]::CreateSpecificCulture("en-us")

add-pssnapin Microsoft.*

$start = (get-date).adddays(-7).toString('MM/dd/yyyy')
$end = (get-date).toString('MM/dd/yyyy')
$filter = "(Received -gt '"+$start+"') -and (Received -lt '"+$end+"')"

New-MailboxExportRequest –Mailbox journal -FilePath "$folder.pst" -ContentFilter "$filter" -confirm:$false -verbose -baditemlimit 1 >>c:\util\journal.txt


$timeout = new-timespan -Minutes 10
$ticker = [diagnostics.stopwatch]::StartNew()

while ($ticker.elapsed -lt $timeout) {    
    $Completed = Get-MailboxExportRequest -mailbox journal | Where {$_.Status -eq “Completed”} >>c:\util\journal.txt
       if ($Completed) {      
              search-mailbox -identity journal -searchquery "Received:($start..$end)"  -deletecontent >>c:\util\journal.txt -force      
              return        
        }    
       start-sleep -seconds 60
 }


#====================end-of-script================================
0
 
LVL 3

Expert Comment

by:Rezwan Islam
ID: 40602510
$today = Get-Date -Format "MMddyyyy"
$Folder = "\\10.2.8.20\volume_1\email\journal\journal-$today"
[System.Reflection.Assembly]::LoadWithPartialName("System.Threading")
[System.Reflection.Assembly]::LoadWithPartialName("System.Globalization")
[System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo]::CreateSpecificCulture("en-us")

add-pssnapin Microsoft.*

$start = (get-date).adddays(-7).toString('MM/dd/yyyy')
$end = (get-date).toString('MM/dd/yyyy')
$filter = "(Received -gt '"+$start+"') -and (Received -lt '"+$end+"')"

New-MailboxExportRequest –Mailbox journal -FilePath "$folder.pst" -ContentFilter "$filter" -confirm:$false -verbose -baditemlimit 1 >>c:\util\journal.txt


$timeout = new-timespan -Minutes 10
$ticker = [diagnostics.stopwatch]::StartNew()

while ($ticker.elapsed -lt $timeout) {    
    $Completed = Get-MailboxExportRequest -mailbox journal | Where {$_.Status -eq “Completed”} >>c:\util\journal.txt
       if ($Completed) {       
              search-mailbox -identity journal -searchquery "Received:($start..$end)"  -deletecontent >>c:\util\journal.txt -force       
              return        
        }     
       start-sleep -seconds 60
 }

Open in new window


just testing to see if I could paste the script like you.
0
 
LVL 23

Author Comment

by:Thomas Grassi
ID: 40604505
Rezwan

thank you for the corrections  it will run on this coming Monday.

I am sure it will work

I added one line to the end

$today = Get-Date -Format "MMddyyyy"
$Folder = "\\10.2.8.20\volume_1\email\journal\journal-$today"
[System.Reflection.Assembly]::LoadWithPartialName("System.Threading")
[System.Reflection.Assembly]::LoadWithPartialName("System.Globalization")
[System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo]::CreateSpecificCulture("en-us")

add-pssnapin Microsoft.*

$start = (get-date).adddays(-7).toString('MM/dd/yyyy')
$end = (get-date).toString('MM/dd/yyyy')
$filter = "(Received -gt '"+$start+"') -and (Received -lt '"+$end+"')"

New-MailboxExportRequest –Mailbox journal -FilePath "$folder.pst" -ContentFilter "$filter" -confirm:$false -verbose -baditemlimit 1 >>c:\util\journal.txt


$timeout = new-timespan -Minutes 10
$ticker = [diagnostics.stopwatch]::StartNew()

while ($ticker.elapsed -lt $timeout) {    
    $Completed = Get-MailboxExportRequest -mailbox journal | Where {$_.Status -eq “Completed”} >>c:\util\journal.txt
       if ($Completed) {       
              search-mailbox -identity journal -searchquery "Received:($start..$end)"  -deletecontent >>c:\util\journal.txt -force       
              return        
        }     
       start-sleep -seconds 60
 }
Get-MailboxExportRequest | Where {$_.Status -eq “Completed”} | Remove-MailboxExportRequest >>c:\util\journal.txt

Open in new window




Any thoughts?
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 3

Expert Comment

by:Rezwan Islam
ID: 40604851
Looks fine to me.

One thing to keep in mind that even if you are exporting 7 days worth of email items net-mailboxexportrequest cmdlet will always move the mailbox to disconnected mailbox folder and the AD account to disabled account OU.

For re-using the mailbox you will have move AD account to the proper OU and reconnect the mailbox to the user account.
0
 
LVL 23

Author Comment

by:Thomas Grassi
ID: 40604902
I have ran this or over two months now and never had that issue

But thanks for the heads up will keep close eye out for that.

One thing to note this is the Exchange Journal mailbox so it is always getting email to it inbox.
0
 
LVL 3

Expert Comment

by:Rezwan Islam
ID: 40604990
You are right. Please ignore the above mailbox disconnection statement.

Just realised it is my other script that was set up for automating user termination process to help service desk guys with archiving and disabling terminated mailbox.

Thanks.
0
 
LVL 23

Author Comment

by:Thomas Grassi
ID: 40605320
Rezwan

No problem  thanks for the update

Hey that other script sounds interesting can you post that?

Thanks
0
 
LVL 3

Expert Comment

by:Rezwan Islam
ID: 40606903
Sure. Here is the script.

#email Stuff
$subject = "Nightly Exchange Cleanup"
$emailto = "user@yourdomain.com"
$emailfrom = "powershell-scripts@yourdomain.com"
$SMTPserver = "smtp.yourdomain.com"
$date = Get-Date -Format dd-mm-yyyy
$mailer = new-object Net.Mail.SMTPclient($SMTPserver)
$htmlHeader = "<html><center><head><style><!--body, table, tr, td {font-family: Verdana, Arial, Helvetica, sans-serif;font-size: 10px}textArea {font-size: 12px;}--></style></head>Disabled Email Account / User Report for "+$date+"<br>The following email accounts have been disabled and the users moved.<br> Please investigate all red entries<body>"
$tableHeader = "<p class='textArea'>$extTitle</p> <table cellpadding=3 cellspacing=1 border=0 bgcolor=6d88ad><tr bgcolor=e5e5e5><td><b>User Name</b></td><td><b>Mailbox Server</b></td><td><b>Mailbox DB</b></td><td><b>Size</b></td><td><b>Status</b></td></tr>"
$body = $htmlHeader+ $tableheader	
$colour = ("#e7e9f2"),("#f5f5f5")
$red = "#CC6666"



# Load Exchange commands
$s = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://yourMailboxServer/powershell
Import-PSSession $s

# Quest AD Management
Add-PSSnapin quest.activeroles.admanagement

#Collect all exports that are currently in the list
$completedExports = Get-MailboxExportRequest #|where {$_.status -eq "completed"} 


foreach ($request in $completedExports)
{
	if ($request.status -eq "completed")
	{
	#remove the export request
	## NOTE this needs to happen before you disable the mailbox due to a bug in SP1
	$request | Remove-MailboxExportRequest -confirm:$false
	
	#Lets get mailbox stats
	$stats = get-mailboxstatistics $request.mailbox
		
	#Disable the mailbox
	Disable-Mailbox $request.mailbox -confirm:$false
	
	#Move user to the disabled OU
	Move-QADObject -identity $request.mailbox -to "yourdomain.com/Disabled Accounts"
 	
	##Complile table in varible for emailing to ITC
	$x+=1
	$altcolour = $colour[($x % 2)] 
	$send=1
	$body = $body+"<tr><tr bgcolor="+$altcolour+"><td>"+$request.mailbox+"</td><td>"+$stats.servername+"</td><td>"+$stats.database+"</td><td>"+$stats.TotalItemSize+"</td><td>"+$request.status+"</td></tr>"
 	}
	else
	{
	# Seems to be items in different status
	$body = $body+"<tr><tr bgcolor="+$red+"><td>"+$request.mailbox+"</td><td>.</td><td>.</td><td>.</td><td>"+$request.status+"</td></tr>"
	}
 }
 
 
 #send the email
$body=$body+"</table><p style=font-family:calibri;font-size:10px;></a></p>"  
$msg = new-object Net.Mail.MailMessage($emailfrom, $emailto, $subject, $body) 
$msg.IsBodyHTML = $true 
Write-Host $body
write-host "____________________________________________________"
write-host "Sending Email to " $emailto
$mailer.send($msg)

Open in new window

0
 
LVL 23

Author Comment

by:Thomas Grassi
ID: 40606938
Rezwan

Great thanks

Will post results on Monday about the journal script also.
0
 
LVL 23

Author Comment

by:Thomas Grassi
ID: 40613108
Rezwan

Sorry to say the script failed again.

It was stuck in a loop was running past 20 minutes.

Job should not take more than a few minutes to run.


This command still not running

 search-mailbox -identity journal -searchquery "Received:($start..$end)"  -deletecontent >>c:\util\journal.txt -force      


I run it manually

Any thoughts?

Here is my code.

$today = Get-Date -Format "MMddyyyy"
$Folder = "\\10.2.8.20\volume_1\email\journal\journal-$today"
[System.Reflection.Assembly]::LoadWithPartialName("System.Threading")
[System.Reflection.Assembly]::LoadWithPartialName("System.Globalization")
[System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo]::CreateSpecificCulture("en-us")

add-pssnapin Microsoft.*

$start = (get-date).adddays(-7).toString('MM/dd/yyyy')
$end = (get-date).toString('MM/dd/yyyy')
$filter = "(Received -gt '"+$start+"') -and (Received -lt '"+$end+"')"

New-MailboxExportRequest –Mailbox journal -FilePath "$folder.pst" -ContentFilter "$filter" -confirm:$false -verbose -baditemlimit 1 >>c:\util\journal.txt


$timeout = new-timespan -Minutes 10
$ticker = [diagnostics.stopwatch]::StartNew()

while ($ticker.elapsed -lt $timeout) {    
    $Completed = Get-MailboxExportRequest -mailbox journal | Where {$_.Status -eq “Completed”} >>c:\util\journal.txt
       if ($Completed) {       
              search-mailbox -identity journal -searchquery "Received:($start..$end)"  -deletecontent >>c:\util\journal.txt -force       
              return        
        }     
       start-sleep -seconds 60
 }
Get-MailboxExportRequest | Where {$_.Status -eq “Completed”} | Remove-MailboxExportRequest >>c:\util\journal.txt

Open in new window

0
 
LVL 3

Accepted Solution

by:
Rezwan Islam earned 500 total points
ID: 40615965
Sorry mate. I was and still am stuck up into a few things.

It seems If ($Completed) not working, can you try

if (Get-MailboxExportRequest -mailbox journal | Where {$_.Status -eq “Completed”})
 instead may be.  If this works we will then have to make ammend to the if statement a bit.

Here is the full script.

$today = Get-Date -Format "MMddyyyy"
$Folder = "\\10.2.8.20\volume_1\email\journal\journal-$today"
[System.Reflection.Assembly]::LoadWithPartialName("System.Threading")
[System.Reflection.Assembly]::LoadWithPartialName("System.Globalization")
[System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo]::CreateSpecificCulture("en-us")

add-pssnapin Microsoft.*

$start = (get-date).adddays(-7).toString('MM/dd/yyyy')
$end = (get-date).toString('MM/dd/yyyy')
$filter = "(Received -gt '"+$start+"') -and (Received -lt '"+$end+"')"

New-MailboxExportRequest –Mailbox journal -FilePath "$folder.pst" -ContentFilter "$filter" -confirm:$false -verbose -baditemlimit 1 >>c:\util\journal.txt


$timeout = new-timespan -Minutes 10
$ticker = [diagnostics.stopwatch]::StartNew()

while ($ticker.elapsed -lt $timeout) {    
    ##$Completed = Get-MailboxExportRequest -mailbox journal | Where {$_.Status -eq “Completed”} >>c:\util\journal.txt
       if (Get-MailboxExportRequest -mailbox journal | Where {$_.Status -eq “Completed”}) {       
              search-mailbox -identity journal -searchquery "Received:($start..$end)"  -deletecontent >>c:\util\journal.txt -force       
              return        
        }     
       start-sleep -seconds 60
 }
Get-MailboxExportRequest | Where {$_.Status -eq “Completed”} | Remove-MailboxExportRequest >>c:\util\journal.txt

Open in new window

0
 
LVL 23

Author Comment

by:Thomas Grassi
ID: 40616378
Rezwan

No problem I know how that is.

Thanks I will try this and will post results
0
 
LVL 23

Author Closing Comment

by:Thomas Grassi
ID: 40626868
Rezwan

Great job

It ran this time

Thanks for all your help
0
 
LVL 23

Author Comment

by:Thomas Grassi
ID: 40627027
Rezwan

this command

Get-MailboxExportRequest | Where {$_.Status -eq “Completed”} | Remove-MailboxExportRequest >>c:\util\journal.txt

did not run

I ran it from the console

and I got a prompt

Y Yes  A Yes to All N No L  No to All

Is there a way to auto respond ?

Thanks
0
 
LVL 23

Author Comment

by:Thomas Grassi
ID: 40627122
Rezwan

Got it -confirm:$false   was what I needed to add to the command line

Thanks
0
 
LVL 3

Expert Comment

by:Rezwan Islam
ID: 40640972
It was a pleasure to work on this script with you. Cheers.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Check out this infographic on what you need to make a good email signature that will work perfectly for your organization.
Follow this checklist to learn more about the 15 things you should never include in an email signature from personal quotes, animated gifs and out-of-date marketing content.
To show how to generate a certificate request in Exchange 2013. We show this process by using the Exchange Admin Center. Log into Exchange Admin Center.:  First we need to log into the Exchange Admin Center. Navigate to the Servers >> Certificates…
The viewer will learn how to dynamically set the form action using jQuery.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now