how to get message subject list from public folder using ews powershell

Hi 

I need to get message subject list from public folder using ews Powershell then i already know to how to bind public folder but i want to know to how to use impersonation and get message subject from public folder Pls help me



        
 

Thanks

Manidurai



  • Edited by manidurai Monday, July 06, 2015 6:20 AM
July 6th, 2015 6:13am

With impersonation and public folders you can't impersonate a Public folder so you have to impersonate a particular Mailbox. Eg if you impersonate UserA then you would be connecting the public Folder as user A and you will get what ever rights UserA has to that particular folder.

You can use a script like this to connect to a public folder and enumerate items

## Get the Mailbox to Access from the 1st commandline argument

$MailboxName = $args[0]

## Load Managed API dll  

###CHECK FOR EWS MANAGED API, IF PRESENT IMPORT THE HIGHEST VERSION EWS DLL, ELSE EXIT
$EWSDLL = (($(Get-ItemProperty -ErrorAction SilentlyContinue -Path Registry::$(Get-ChildItem -ErrorAction SilentlyContinue -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Exchange\Web Services'|Sort-Object Name -Descending| Select-Object -First 1 -ExpandProperty Name)).'Install Directory') + "Microsoft.Exchange.WebServices.dll")
if (Test-Path $EWSDLL)
    {
    Import-Module $EWSDLL
    }
else
    {
    "$(get-date -format yyyyMMddHHmmss):"
    "This script requires the EWS Managed API 1.2 or later."
    "Please download and install the current version of the EWS Managed API from"
    "http://go.microsoft.com/fwlink/?LinkId=255472"
    ""
    "Exiting Script."
    exit
    } 

## Set Exchange Version  
$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  
$psCred = Get-Credential  
$creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())  
$service.Credentials = $creds      

#Credentials Option 2  
#service.UseDefaultCredentials = $true  

## Choose to ignore any SSL Warning issues caused by Self Signed Certificates  

## Code From http://poshcode.org/624
## 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

## end code from http://poshcode.org/624

## 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  

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

#CAS URL Option 2 Hardcoded  

#$uri=[system.URI] "https://casservername/ews/exchange.asmx"  
#$service.Url = $uri    

## Optional section for Exchange Impersonation  

#$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName) 

function FolderIdFromPath{
    param (
            $FolderPath = "$( throw 'Folder Path is a mandatory Parameter' )"
          )
    process{
        ## Find and Bind to Folder based on Path  
        #Define the path to search should be seperated with \  
        $folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::PublicFoldersRoot)   
        $tfTargetFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
        #Split the Search path into an array  
        $fldArray = $FolderPath.Split("\") 
         #Loop through the Split Array and do a Search for each level of folder 
        for ($lint = 1; $lint -lt $fldArray.Length; $lint++) { 
            #Perform search based on the displayname of each folder level 
            $fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1) 
            $SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,$fldArray[$lint]) 
            $findFolderResults = $service.FindFolders($tfTargetFolder.Id,$SfSearchFilter,$fvFolderView) 
            if ($findFolderResults.TotalCount -gt 0){ 
                foreach($folder in $findFolderResults.Folders){ 
                    $tfTargetFolder = $folder                
                } 
            } 
            else{ 
                "Error Folder Not Found"  
                return $null
            }     
        }  
        if($tfTargetFolder -ne $null){
            return $tfTargetFolder.Id.UniqueId.ToString()
        }
    }
}
#Example use
$fldId = FolderIdFromPath -FolderPath "\folder1\folder2\folder3"
$SubFolderId =  new-object Microsoft.Exchange.WebServices.Data.FolderId($fldId)
$SubFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$SubFolderId)
if($SubFolder -ne $null){
    #Define ItemView to retrive just 1000 Items    
    $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
    $fiItems = $null    
    do{    
        $fiItems = $service.FindItems($SubFolder.Id,$ivItemView)    
        #[Void]$service.LoadPropertiesForItems($fiItems,$psPropset)  
        foreach($Item in $fiItems.Items){      
                    $Item.Subject + " " + $Item.Start    
        }    
        $ivItemView.Offset += $fiItems.Items.Count    
    }while($fiItems.MoreAvailable -eq $true) 
}

There is code in that script to use impersonation but it commented out

Cheers
Glen

  • Marked as answer by manidurai 3 hours 9 minutes ago
Free Windows Admin Tool Kit Click here and download it now
July 6th, 2015 11:06am

With impersonation and public folders you can't impersonate a Public folder so you have to impersonate a particular Mailbox. Eg if you impersonate UserA then you would be connecting the public Folder as user A and you will get what ever rights UserA has to that particular folder.

You can use a script like this to connect to a public folder and enumerate items

## Get the Mailbox to Access from the 1st commandline argument

$MailboxName = $args[0]

## Load Managed API dll  

###CHECK FOR EWS MANAGED API, IF PRESENT IMPORT THE HIGHEST VERSION EWS DLL, ELSE EXIT
$EWSDLL = (($(Get-ItemProperty -ErrorAction SilentlyContinue -Path Registry::$(Get-ChildItem -ErrorAction SilentlyContinue -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Exchange\Web Services'|Sort-Object Name -Descending| Select-Object -First 1 -ExpandProperty Name)).'Install Directory') + "Microsoft.Exchange.WebServices.dll")
if (Test-Path $EWSDLL)
    {
    Import-Module $EWSDLL
    }
else
    {
    "$(get-date -format yyyyMMddHHmmss):"
    "This script requires the EWS Managed API 1.2 or later."
    "Please download and install the current version of the EWS Managed API from"
    "http://go.microsoft.com/fwlink/?LinkId=255472"
    ""
    "Exiting Script."
    exit
    } 

## Set Exchange Version  
$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  
$psCred = Get-Credential  
$creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())  
$service.Credentials = $creds      

#Credentials Option 2  
#service.UseDefaultCredentials = $true  

## Choose to ignore any SSL Warning issues caused by Self Signed Certificates  

## Code From http://poshcode.org/624
## 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

## end code from http://poshcode.org/624

## 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  

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

#CAS URL Option 2 Hardcoded  

#$uri=[system.URI] "https://casservername/ews/exchange.asmx"  
#$service.Url = $uri    

## Optional section for Exchange Impersonation  

#$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName) 

function FolderIdFromPath{
    param (
            $FolderPath = "$( throw 'Folder Path is a mandatory Parameter' )"
          )
    process{
        ## Find and Bind to Folder based on Path  
        #Define the path to search should be seperated with \  
        $folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::PublicFoldersRoot)   
        $tfTargetFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
        #Split the Search path into an array  
        $fldArray = $FolderPath.Split("\") 
         #Loop through the Split Array and do a Search for each level of folder 
        for ($lint = 1; $lint -lt $fldArray.Length; $lint++) { 
            #Perform search based on the displayname of each folder level 
            $fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1) 
            $SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,$fldArray[$lint]) 
            $findFolderResults = $service.FindFolders($tfTargetFolder.Id,$SfSearchFilter,$fvFolderView) 
            if ($findFolderResults.TotalCount -gt 0){ 
                foreach($folder in $findFolderResults.Folders){ 
                    $tfTargetFolder = $folder                
                } 
            } 
            else{ 
                "Error Folder Not Found"  
                return $null
            }     
        }  
        if($tfTargetFolder -ne $null){
            return $tfTargetFolder.Id.UniqueId.ToString()
        }
    }
}
#Example use
$fldId = FolderIdFromPath -FolderPath "\folder1\folder2\folder3"
$SubFolderId =  new-object Microsoft.Exchange.WebServices.Data.FolderId($fldId)
$SubFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$SubFolderId)
if($SubFolder -ne $null){
    #Define ItemView to retrive just 1000 Items    
    $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
    $fiItems = $null    
    do{    
        $fiItems = $service.FindItems($SubFolder.Id,$ivItemView)    
        #[Void]$service.LoadPropertiesForItems($fiItems,$psPropset)  
        foreach($Item in $fiItems.Items){      
                    $Item.Subject + " " + $Item.Start    
        }    
        $ivItemView.Offset += $fiItems.Items.Count    
    }while($fiItems.MoreAvailable -eq $true) 
}

There is code in that script to use impersonation but it commented out

Cheers
Glen

  • Marked as answer by manidurai Wednesday, July 08, 2015 4:18 AM
July 6th, 2015 11:06am

Hi Glen 

it's work for me i have one more doubt that is how to bind all mailbox folder using EWS ,then try with Inbox ,Sentitems,Deleteitems it's working but my need is bind all mailbox folder without giving  folder name Like Inbox,setitems,etc..  pls help me 

i use following code 

## Get the Mailbox to Access from the 1st commandline argument

#$MailboxName = 'william@xlc.local'

#$Range = "07/01/2015..07/01/2015"    
#$AQSString = "System.Message.DateReceived:" + $Range  

## Load Managed API dll  
Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"  
  
## Set Exchange Version  
$ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010 
  
## 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  
#$psCred = Get-Credential  
#$creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())  
#$service.Credentials = $creds 
#$service.Credentials = new-object Microsoft.Exchange.WebServices.Data.WebCredentials("superadmin@xlc.local","Password1234")     
  
#Credentials Option 2  
$service.UseDefaultCredentials = $true  
  
## Choose to ignore any SSL Warning issues caused by Self Signed Certificates  
  
## Code From http://poshcode.org/624
## 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

## end code from http://poshcode.org/624
  
## 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  
  
#CAS URL Option 1 Autodiscover  
#$service.AutodiscoverUrl($MailboxName,{$true})  
#"Using CAS Server : " + $Service.url   
   
#CAS URL Option 2 Hardcoded  
  
$uri=[system.URI] "https://localhost/ews/exchange.asmx"  
$service.Url = $uri    
  
## Optional section for Exchange Impersonation  
  
#$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName) 
function Process-Mailbox{    
    param (    
            $SmtpAddress = "$( throw 'SMTPAddress is a mandatory Parameter' )"    
          )    
    process{    
      

# Bind to the Inbox Folder
$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox, $SmtpAddress)   
$Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
$psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)  
$psPropset.RequestedBodyType = [Microsoft.Exchange.WebServices.Data.BodyType]::Text

#Define ItemView to retrive just 1000 Items    
$ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
$fiItems = $null    
  
    $fiItems = $service.FindItems($Inbox.Id,$ivItemView) 
      If($fiItems -ne $null)
{   
    [Void]$service.LoadPropertiesForItems($fiItems,$psPropset)  
    foreach($Item in $fiItems.Items){ 

$Attachment = ''
              foreach($attach in $Item.Attachments){
               If($Attachment) {
             $Attachment=$Attachment + ";" + $attach.Name.ToString()
                               } 
             Else {
             $Attachment=$attach.Name.ToString()
                   }
                                   }

$rec = ''
              foreach($r in $Item.ToRecipients){
               If($rec) {
             $rec=$rec + ";" + $r.ToString()
                               } 
             Else {
             $rec=$r.ToString()
                   }
                                   }

                        New-Object -TypeName PSObject -Property @{       
                        Date= $Item.DateTimeReceived 
                        Sender =$Item.sender               
                        Recevier = $rec    
                        MessageSubject =$Item.Subject
                        Messagebody =$Item.Body.Text 
                        Attachment = $Attachment 
                            }

                }
                
}
}
}



$(Get-Mailbox | foreach-object {
    $SmtpAddress = $_.WindowsEmailAddress.ToString()    
    if($service.url -eq $null){    
        $service.AutodiscoverUrl($SmtpAddress,{$true})     
        "Using CAS Server : " + $Service.url     
    }    
    Try{    
        $service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $SmtpAddress)   
  
        Process-Mailbox -SmtpAddress $SmtpAddress    
    }    
    catch{    
       # Write-host ("Error processing Mailbox : " + $SmtpAddress + $_.Exception.Message.ToString())    
        $Error.Clear()  
    }    
})|select Date,Sender,recevier,Messagesubject,Messagebody,Attachment 
                                                               
           

Thanks

Manidurai


Free Windows Admin Tool Kit Click here and download it now
July 8th, 2015 12:31am

Hi Glen 

Thanks that is working 

Thanks

Manidurai

July 8th, 2015 9:20am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics