Need some help running powershell commands on exchange

bankadmin
bankadmin used Ask the Experts™
on
I am attempting to search all mailboxes using powershell in exchange 2013 for a attachment or subject would probably work also. I can seem to get it to run
Get-Mailbox | Search-Mailbox -SearchQuery 'subject or attachment name' -TargetMailbox "Discovery Search Mailbox" -TargetFolder "AllMailboxes-Election" -LogLevel Full

It breaks on "discovery search mailbox" I have tried it like this also "DiscoverySearchMailbox"
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Did you create a mailbox called "Discovery Search Mailbox". The TargetMailbox can be any mailbox you want to copy the search results to but it must be a mailbox that exists.
timgreen7077Exchange Engineer
Distinguished Expert 2018

Commented:
Run the below cmdlets in the exchange management shell to get the name of your discovery mailbox if it exists:


Get-Mailbox -ResultSize unlimited | where {$_.name -like "*discover*"} | fl name, alias

If the discover mailbox exists this will give you the correct name and alias and then you can use either for you script.

Author

Commented:
Where would the results of the command be saved to I cant find them
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

timgreen7077Exchange Engineer
Distinguished Expert 2018

Commented:
it will show on the screen

Author

Commented:
It came back with now results the command completed successfully (well no errors) then it just came back to the prompt
timgreen7077Exchange Engineer
Distinguished Expert 2018

Commented:
Then most likely you don't have a discovery mailbox. See below image for example of what will be returned. If its empty then you probably don't have a discovery mailbox, so you will need the results of your query to go to a mailbox that exists.

example

Author

Commented:
So if I point the results to my mailbox what can I expect? An email with the logs of the results of the search?
timgreen7077Exchange Engineer
Distinguished Expert 2018

Commented:
Yes you can point it to your mailbox and a folder, but add the parameter -logonly so that you don't get the emails but just the log.
This is a little more than you were looking for but it is a script I wrote not too long ago and should help :

Write-Host "#############################################################################"
write-host ""
Write-Host "Exchange Search and Remove Script"
Write-Host ""
Write-Host "This script is Designed to Retreive, Copy, and Delete information from Exchange Mailboxes."

Write-Host "#############################################################################"


$Answers = ""|select runscope,LogLevel_Enable_Full,LogLevel_Enable_Basic,TargetMailboxFolder_Query,TargetMailboxFolder_Orig,TargetMailboxFolder_Reply,TargetMailbox_Query_Orig,TargetMailbox_Query,TargetMailbox_Query_Reply,ReviewReponse, ReviewReponse2,identity,Identity_orig,CC_Query,Import_FileName,Import_Query,Import_Query_Reply,CC_Query_Reply,CC_Query_Reply_Orig,From_Query,From_Query_Reply_Orig,From_Query_Reply,Date_Query_Reply_Orig,Date_Query,Date_Query_Reply,Subject_Query,Subject_Query_Reply_Orig,Subject_Query_Reply,Individual_Default_String,Buildstring,SearchQuery,Buildstring1,Buildstring2,loglevel_Query,LogLevel_Reply,LogLevel_Enable,CommandString,CommandString1,CommandString2,CommandString3
$Answers.RunScope = $null
$Answers.ReviewReponse = $null
$answers.identity = $null
$Answers.Identity_orig = $null
$Answers.Import_Query = $null
$Answers.Import_FileName = $null
$Answers.CC_Query = $null
$Answers.CC_Query_Reply_Orig = $null
$Answers.CC_Query_Reply = $null
$Answers.From_Query = $null
$Answers.From_Query_Reply_Orig = $null
$Answers.From_Query_Reply = $null
$Answers.Date_Query = $null
$Answers.Date_Query_Reply_Orig = $null
$Answers.Date_Query_Reply = $null
$Answers.Subject_Query = $null
$Answers.Subject_Query_Reply_Orig = $null
$Answers.Subject_Query_Reply = $null
$Answers.Individual_Default_String = $null
$Answers.Buildstring1 = "Search-Mailibox"
$Answers.Buildstring2 = "Get-Mailbox -ResultSize unlimited |"
$Answers.CommandString = $null
$Answers.CommandString1 = $null
$Answers.CommandString2 = $null
$Answers.CommandString3 = $null
#$Answers.Search_Mailbox = "Search-Mailbox "
#Build Search Query then place in '$searchquery'
$Answers.SearchQuery = " -SearchQuery "
$Answers.LogLevel_Query = "1"
$Answers.LogLevel_Reply = "2"
$Answers.LogLevel_Enable_Full = " -LogLevel Full"
$Answers.LogLevel_Enable_Basic = " -LogLevel Basic"

Function Pause ($Message = "Press any key to continue...") {
   # Check if running in PowerShell ISE
   If ($psISE) {
      # "ReadKey" not supported in PowerShell ISE.
      # Show MessageBox UI
      $Shell = New-Object -ComObject "WScript.Shell"
      $Button = $Shell.Popup("Click OK to continue.", 0, "Hello", 0)
      Return
   }
 
   $Ignore =
      16,  # Shift (left or right)
      17,  # Ctrl (left or right)
      18,  # Alt (left or right)
      20,  # Caps lock
      91,  # Windows key (left)
      92,  # Windows key (right)
      93,  # Menu key
      144, # Num lock
      145, # Scroll lock
      166, # Back
      167, # Forward
      168, # Refresh
      169, # Stop
      170, # Search
      171, # Favorites
      172, # Start/Home
      173, # Mute
      174, # Volume Down
      175, # Volume Up
      176, # Next Track
      177, # Previous Track
      178, # Stop Media
      179, # Play
      180, # Mail
      181, # Select Media
      182, # Application 1
      183  # Application 2
 
   Write-Host -NoNewline $Message
   While ($KeyInfo.VirtualKeyCode -Eq $Null -Or $Ignore -Contains $KeyInfo.VirtualKeyCode) {
      $KeyInfo = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
   }
}



#Import Existing Search
Function get-ExImportFile(){
$Answers.Import_Query = Read-Host -Prompt "Would you Like to Import a previously saved Search : [enter] YES[1] OR NO[2]"
	switch($Answers.Import_Query){
		1{$Answers.Import_FileName = Read-Host -Prompt "Enter File Name *Note:File must reside in the same location as you are ""Locally"" running the script from"
			import-clixml -path $($answers.Import_FileName)
			
			}
		2{$Answers.Import_Query = $null}
	default {$Answers.Import_Query = $null}
	}
}

Function get-Exrunscope(){
$Answers.RunScope = Read-Host -Prompt "Two Run Modes (Single or All) : [enter] Single[S] | All[A]"
	switch ($Answers.runscope){
		S {$answers.identity = Read-host -Prompt "[Enter] Mailbox Name"
				$answers.identity_Orig = $answers.identity
				Write-Host "You Entered ""$($answers.identity)"""
				$answers.Identity = ($answers.identity).Replace($($answers.identity), " -Identity ""$($answers.identity)""")}
		A {$answers.identity = "Global"
				Write-Host "You have Chosen To Run this script Globally on All mailboxes"}
	default {$answers.identity = Read-host -Prompt "[Enter] Mailbox Name"
				Write-Host "You Entered ""$($answers.identity)"""
			$answers.identity = ($answers.identity).Replace($($answers.identity), " -Identity ""$($answers.identity)""")}
	}
}





#Target Mailbox and Folder:
Function get-targetMailbox(){

$Answers.TargetMailbox_Query = 1
	$Answers.TargetMailbox_Query = Read-Host -Prompt "Please enter the Target Mailbox you would like to Copy your results to: [Example] Johndoe@test.com"
	$answers.TargetMailbox_Query_Orig = $answers.TargetMailbox_Query
	$answers.TargetMailbox_Query_Reply = ($answers.TargetMailbox_Query).Replace($($answers.TargetMailbox_Query), " -TargetMailbox ""$($answers.TargetMailbox_Query)""")

	$Answers.TargetMailboxFolder_Query = 1
	$Answers.TargetMailboxFolder_Query = Read-Host -Prompt "Please Enter the Folder in the target Mailbox $($TargetMailbox_Query_Orig): [Example] Archive"
	$answers.TargetMailboxFolder_Orig = $answers.TargetMailboxFolder_Query
	$answers.TargetMailboxFolder_Reply = ($answers.TargetMailboxFolder_Query).Replace($($answers.TargetMailboxFolder_Query), " -TargetFolder ""$($answers.TargetMailboxFolder_Query)""")}

#Are you Going to use CC'd Individuals to identity the message
Function get-ExCCquery(){
$Answers.CC_Query = Read-Host -Prompt "Would you like to Search by CC'd Content: [enter] YES[1] | NO[2]"
	switch($Answers.CC_Query){
		1{$Answers.CC_Query_Reply = Read-Host -Prompt "Enter Search Criteria:"
			$answers.CC_Query_Reply_Orig = $answers.CC_Query_Reply
			$answers.CC_Query_Reply = ($answers.CC_Query_Reply).Replace($($answers.CC_Query_Reply), " cc:""$($answers.CC_Query_Reply)""")}
		2{$Answers.CC_Query_Reply = $null}
	default {$Answers.CC_Query_Reply = $null}
	}
}

#Get From Information
Function get-ExFromquery(){
	$Answers.From_Query = 1
	$Answers.From_Query_Reply = Read-Host -Prompt "Who is this Message From [Example] Jdoe@test.com"
	$answers.From_Query_Reply_Orig = $answers.From_Query_Reply
	$answers.From_Query_Reply = ($answers.From_Query_Reply).Replace($($answers.From_Query_Reply), " From:""$($answers.From_Query_Reply)""")}



#Are you Going to use the Date to Identity the Message?
Function get-ExDate(){
$Answers.Date_Query = Read-Host -Prompt "Would you like to Search by Date Sent: [enter] YES[1] | NO[2]"
	switch($Answers.Date_Query){
		1{$Answers.Date_Query_Reply = Read-Host -Prompt "Enter Search Criteria: Note:Date must be Entered in MM/DD/yyyy format"
			$answers.Date_Query_Reply_Orig = $answers.Date_Query_Reply
			$Answers.Date_Query_Reply = ($Answers.Date_Query_Reply).Replace($($Answers.Date_Query_Reply), " Sent:$($Answers.Date_Query_Reply)")}
		2{$Answers.Date_Query_Reply = $null}
	default {$Answers.Date_Query_Reply = $null}
	}
}

#Are you Going to use the Subject to Identity the Message?
Function get-ExSubject(){
$Answers.Subject_Query = Read-Host -Prompt "Would you like to Search by Subject Content [enter] YES[1] | NO[2]"
	switch($Answers.Subject_Query){
		1{$Answers.Subject_Query_Reply = Read-Host -Prompt "Enter Search Criteria:"
			$answers.Subject_Query_Reply_Orig = $answers.subject_Query_Reply
			$Answers.Subject_Query_Reply = ($Answers.Subject_Query_Reply).Replace($($Answers.Subject_Query_Reply), " Subject:""$($Answers.Subject_Query_Reply)""")}
		2{$Answers.Subject_Query_Reply = $null}
	default {$Answers.Subject_Query_Reply = $null}
	}
}
#get-ExImportFile


get-Exrunscope
get-targetMailbox
get-ExFromquery
get-ExCCquery
get-ExDate
get-ExSubject


#Build Dynamically Updating String:
function create-SearchQuery(){
$keys = $answers.psobject.Properties |
    Where {$_.Value -like "1"} | 
    Select Name
$answers.buildstring = $null
$Answers.SearchQuery = " -SearchQuery "
$keys | ForEach {
    $answers.Buildstring += $answers.psobject.Properties["$($_.Name)_Reply"].value}

$answers.Buildstring = ($answers.buildstring).Trim()
$answers.Searchquery = $answers.SearchQuery + ($answers.buildstring).replace($($answers.buildstring), "'$($answers.buildstring)'")
}

. Create-SearchQuery

#Build Logic for Complete Command String

    function create-ExCommandString(){
    if ($Answers.runscope -eq "S"){
		$Answers.CommandString = "Search-Mailbox$($answers.identity)$($Answers.SearchQuery)$($answers.TargetMailbox_Query_Reply)$($answers.TargetMailboxFolder_Reply)"
		$Answers.CommandString1 = "Search-Mailbox$($answers.identity)$($Answers.SearchQuery) -EstimateResultOnly"
        $Answers.CommandString2 = "Search-Mailbox$($answers.identity)$($Answers.SearchQuery)$($answers.TargetMailbox_Query_Reply)$($answers.TargetMailboxFolder_Reply) -DeleteContent"
        $Answers.CommandString3 = "Search-Mailbox$($answers.identity)$($Answers.SearchQuery)$($answers.TargetMailbox_Query_Reply)$($answers.TargetMailboxFolder_Reply) -LogOnly"
    }

	if ($Answers.runscope -eq "A"){
		$Answers.CommandString = "Get-Mailbox -ResultSize unlimited |Search-Mailbox$($answers.SearchQuery)$($answers.TargetMailbox_Query_Reply)$($Answers.TargetMailboxFolder_Reply)"
		$Answers.CommandString1 = "Get-Mailbox -ResultSize unlimited |Search-Mailbox$($answers.SearchQuery) -EstimateResultOnly"
        $Answers.CommandString2 = "Get-Mailbox -ResultSize unlimited |Search-Mailbox$($answers.SearchQuery)$($answers.TargetMailbox_Query_Reply)$($Answers.TargetMailboxFolder_Reply) -DeleteContent"
        $Answers.CommandString3 = "Get-Mailbox -ResultSize unlimited |Search-Mailbox$($answers.SearchQuery)$($answers.TargetMailbox_Query_Reply)$($Answers.TargetMailboxFolder_Reply) -LogOnly"
        }
         if ($Answers.loglevel_Query -eq "1"){ 
            if ($Answers.Loglevel_Reply -eq "1"){
                $Answers.Commandstring = "$($Answers.Commandstring)$($Answers.LogLevel_Enable_Basic)"
                $Answers.Commandstring1 = "$($Answers.Commandstring1)"
                $Answers.Commandstring2 = "$($Answers.Commandstring2)$($Answers.LogLevel_Enable_Basic)"
                $Answers.Commandstring3 = "$($Answers.Commandstring3)$($Answers.LogLevel_Enable_Basic)"
            }
            if ($Answers.Loglevel_Reply -eq "2"){
                $Answers.Commandstring = "$($Answers.Commandstring)$($Answers.LogLevel_Enable_Full)"
                $Answers.Commandstring1 = "$($Answers.Commandstring1)"
                $Answers.Commandstring2 = "$($Answers.Commandstring2)$($Answers.LogLevel_Enable_Full)"
                $Answers.Commandstring3 = "$($Answers.Commandstring3)$($Answers.LogLevel_Enable_Full)"
            }
        }
    }

    . create-ExCommandString
#invoke-expression $Answers.CommandString

#Options Review : 

Write-Host "#############################################################################"
Write-Host "Please review this information and ensure it is correct"
Write-Host "#############################################################################"
$answers | Select-Object -Property `
@{n = 'Run Scope'; e = {$($Answers.runscope)}},
@{n = 'Logging'; e = {$($Answers.LogLevel_Query)}},
@{n = 'Logging Type'; e = {$($answers.Loglevel_Reply)}},
@{n = 'Search Mailbox'; e = {$($answers.identity_Orig)}},
@{n = 'Target Mailbox:Copy'; e = {$($Answers.TargetMailbox_Query_Orig)}},
@{n = 'Target Folder:Copy'; e = {$($Answers.TargetMailboxFolder_Orig)}},
@{n = 'From'; e = {$($answers.From_Query_Reply_Orig)}},
@{n = 'CC'; e = {$($answers.CC_Query_Reply_Orig)}},
@{n = 'Subject'; e = {$($answers.Subject_Query_Reply_Orig)}}

Function get-reviewInput(){
$Answers.ReviewReponse = Read-Host -Prompt "Was the information Correct [enter] YES[1] | NO[2]"
	switch($Answers.ReviewReponse){
		1{
			Write-Host "#####################################################################################################"
			Write-Host "The script is Continuing to Process"
			Write-Host "#####################################################################################################"
			
			Start-Transcript -Path "$pwd\ExchangeDelete.txt"
			
			$commandstring1 = invoke-expression $Answers.CommandString3
			write-host "Mailbox's Found that Match the Criteria"
			$commandstring1 |? {$_.ResultItemsCount -ge "1"}|select DisplayName, ResultItemsCount, ResultItemsSize

			Stop-Transcript
			Write-Host "#####################################################################################################"
			Write-Host "Please review the Logs in your Archive Folder at the Following Location"
			Write-Host "Archive Account Location = $($Answers.TargetMailbox_Query_Orig)"
			Write-Host "Archive Folder  Location = $($Answers.TargetMailboxFolder_Orig)"
			Write-Host "#####################################################################################################"
			pause}

		2{
			Write-Host "#####################################################################################################"
			Write-Host "The script will End in 15 seconds to prevent Data Loss due to Bad Input"
			Write-Host "#####################################################################################################"
			Start-Sleep 15
			Exit}
	}
}

. get-reviewInput
		
Function get-reviewInput2(){
$Answers.ReviewReponse2 = Read-Host -Prompt "Please Review:  [enter] COPY[1] | DEL[2] | EXIT[3]"
	switch($Answers.ReviewReponse2){
		1{
			Write-Host "#####################################################################################################"
			Write-Host "The Script will Now Copy the Content to the Location you Specified in the Archive Folder"
			Write-Host "#####################################################################################################"
			
			Start-Transcript -Path "$pwd\ExchangeDelete3.txt"
			invoke-expression $Answers.CommandString
			get-reviewInput2

			}
		2{
			Write-Host "##########################################################################################################"
			Write-Host "The script will Delete the Discovered content from the following Mailboxes"
			write-host "************    THIS MAY RESULT IN DATA LOSS    ****************"
			write-host "THIS CONTENT WHEN DELETED WILL NEED TO BE RECOVERED FROM BACKUP IF REQUIRED IN THE FUTURE"
			write-host "************    THIS MAY RESULT IN DATA LOSS    ****************"
			write-host "$($commandstring1 |? {$_.ResultItemsCount -ge "1"}|select DisplayName, ResultItemsCount, ResultItemsSize)"
			write-host ""
			write-host "*** LAST CHANCE *** THIS SCRIPT WILL PAUSE. iF YOU ARE SURE YOU CAN CONTINUE"
			write-host ""
			Write-Host "##########################################################################################################"
			
			Pause
			
			Start-Transcript -Path "$pwd\ExchangeDelete3.txt"
			invoke-expression $Answers.CommandString2
			get-reviewInput2
			}
		3{
			Write-Host "#####################################################################################################"
			Write-Host "The script will End in 15 seconds due to Option ""NO"" Being Selected"
			Write-Host "#####################################################################################################"
			Start-Sleep 5
			Exit}
	}
}
get-reviewInput2
Start-sleep 5

Open in new window

@bankadmin

To answer the question you posed above.

Here are the syntax's that you use from the command line:

#Single Mailbox
#Search-Mailbox -Identity <name> -SearchQuery subject:"<verbatim subject line>" -TargetMailbox <name of mailbox> -TargetFolder <name of folder> -LogOnly -LogLevel Full

#All Mailboxes
#Get-Mailbox -ResultSize unlimited | Search-Mailbox -SearchQuery attachment:<filename> -TargetMailbox <name of mailbox> -TargetFolder <name of folder> -LogOnly -LogLevel Full

#Find and Delete Specific Text in Subject:
#Get-Mailbox -ResultSize unlimited | Search-Mailbox -SearchQuery subject:<verbatim subject line> -DeleteContent

#Copy Message Before Deletion :
#Get-Mailbox -ResultSize unlimited | Search-Mailbox -SearchQuery subject:<verbatim subject line> -TargetMailbox <name of mailbox> -TargetFolder <name of folder> -DeleteContent

#Copy Message  Send them to Admin Mailbox and Delete from User Mailbox :
#Get-Mailbox -ResultSize unlimited | Search-Mailbox -SearchQuery subject:"Download this file" -TargetMailbox Administrator -TargetFolder DeletedMessages -DeleteContent

Open in new window

Author

Commented:
Thanks for all the suggestions and sorry for the delay I left for a vacation shortly after posting this question

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial