Link to home
Start Free TrialLog in
Avatar of Mike
MikeFlag for United States of America

asked on

Need to Find a Powershell script

Greeting Experts,
      I am in the need of a Power Shell script that is able to pull email attachments from a specified email folder in Windows Office 2007. Every day, I receive 8 to 10 different reports (Mostly Sent in the Early Morning) from different people. The time it takes me to click each individual email, open, and Save the attachment (Excel & Word documents) can take big chuck of my time every day.  Currently, I have 3 different email folders created (Region 1, Region 2, and Region 3) in Windows outlook 2007. When one of the specified emails is received a rule directs the email in to one of the 3 folders based on the “sender’s” email address (Region1Admins@domain.com). I would like to find a script to scan that scan that folder and pull those attachments to a file directory on my computer. Does anybody have an idea how this can be done…
Avatar of SubSun
SubSun
Flag of India image

For Exchange 2007 and 2010 you can access the mailbox using PowerShell and EWS. Please refer the link for sample script..
http://social.technet.microsoft.com/Forums/en-US/exchange2010/thread/c4d4cca8-2bc0-48a9-97f8-61fc68c8079c/
Avatar of Mike

ASKER

Hello subsun,
      I looked at the script you suggested and I am little confused with it… how does the “EWS” tie in when connecting to Exchange Server (Using Exchange 2010). I guess just not sure where I need to adjust the code….


 

################################################
#
#Accept any certificates presented by the CAS
#
################################################

## Create a compilation environment
$Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
$Compiler=$Provider.CreateCompiler()
$Params=New-Object System.CodeDom.Compiler.CompilerParameters
$Params.GenerateExecutable=$False
$Params.GenerateInMemory=$True
$Params.IncludeDebugInformation=$False
$Params.ReferencedAssemblies.Add("System.DLL") | Out-Null

$TASource=@'
  namespace Local.ToolkitExtensions.Net.CertificatePolicy{
    public class TrustAll : System.Net.ICertificatePolicy {
      public TrustAll() { 
      }
      public bool CheckValidationResult(System.Net.ServicePoint sp,
        System.Security.Cryptography.X509Certificates.X509Certificate cert, 
        System.Net.WebRequest req, int problem) {
        return true;
      }
    }
  }
'@ 
$TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
$TAAssembly=$TAResults.CompiledAssembly

## We now create an instance of the TrustAll and attach it to the ServicePointManager
$TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
[System.Net.ServicePointManager]::CertificatePolicy=$TrustAll

################################################
#
#Load the EWS API and connect to the CAS/EWS
# EWS API is found at: http://www.microsoft.com/en-us/download/details.aspx?id=28952
#
################################################

## Load Managed API dll
Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"

## Set Exchange Version (Exchange2010, Exchange2010_SP1 or Exchange2010_SP2)
$ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2

## Create Exchange Service Object
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)

## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials
#Credentials Option 1 using UPN for the windows Account
$creds = New-Object System.Net.NetworkCredential("USERNAME","PASSWORD","DOMAIN") 
$service.Credentials = $creds  

#Credentials Option 2
#service.UseDefaultCredentials = $true

## Set the URL of the CAS (Client Access Server) to use two options are availbe to use Autodiscover to find the CAS URL or Hardcode the CAS to use

$MailboxName = "user@domain.com"

#CAS URL Option 1 Autodiscover
#$service.AutodiscoverUrl($MailboxName,{$true})
#"Using CAS Server : " + $Service.url 

#CAS URL Option 2 Hardcoded  
$uri=[system.URI] "https://<FQDN>/ews/Exchange.asmx"
$service.Url = $uri  


#Bind to the Inbox folder
$Sfha = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::HasAttachments, $true)
$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,"user@domain.com")   
$Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  

####################################################################################################
#
#This section finds attachments and copies the attachment to the download directory
#
####################################################################################################


$ivItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(100)
$downloadDirectory = "directory name, UNC will work"

$findItemsResults = $Inbox.FindItems($Sfha,$ivItemView)
foreach($miMailItems in $findItemsResults.Items){
	$miMailItems.Load()
	foreach($attach in $miMailItems.Attachments){
		$attach.Load()
		$fiFile = new-object System.IO.FileStream(($downloadDirectory + “\” + $attach.Name.ToString()), [System.IO.FileMode]::Create)
		$fiFile.Write($attach.Content, 0, $attach.Content.Length)
		$fiFile.Close()
		write-host "Downloaded Attachment : " + (($downloadDirectory + “\” + $attach.Name.ToString()))
	}
}

####################################################################################################
#
#This section moves emails from the Inbox to a subfolder of "Inbox" called "PROCESSED", make sure to 
#create the folder.
#
####################################################################################################

#Get the ID of the folder to move to  
$fvFolderView =  New-Object Microsoft.Exchange.WebServices.Data.FolderView(100)  
$fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Shallow;
$SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,"PROCESSED")
$findFolderResults = $Inbox.FindFolders($SfSearchFilter,$fvFolderView)  
  
#Define ItemView to retrive just 100 Items    
$ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(100)  
$fiItems = $null    
do{    
    $fiItems = $Inbox.FindItems($Sfha,$ivItemView)   
    #[Void]$service.LoadPropertiesForItems($fiItems,$psPropset)  
        foreach($Item in $fiItems.Items){      
            # Copy the Message  
            #$Item.Copy($findFolderResults.Folders[0].Id)  
            # Move the Message  
            $Item.Move($findFolderResults.Folders[0].Id)  
        }    
        $ivItemView.Offset += $fiItems.Items.Count    
    }while($fiItems.MoreAvailable -eq $true)  

Open in new window

For manual extraction of attachments of emails in a folder I like to use Outlook Attachment Remover.
There is also an article on EE (Export or Strip Email Attachments in Outlook) for coding an action yourself in VBA.
ASKER CERTIFIED SOLUTION
Avatar of SubSun
SubSun
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Mike

ASKER

Ok..... I let you know how I make out.....
Avatar of Mike

ASKER

This worked... thanks...