Get items in all Outlook folders using EWS (PowerShell)

Hi All,
I'm trying to figure out how to search all items in Outlook mailbox using EWS. I have a script that currently search "Sent Items" only. See script below. I just need to modify it to search all folders instead. Any help is appreciated. Thank you
$Report = @()
#Provide text files for all users in the legal department
$Law = cat law.txt
#Set Date to 1 Year Ago
$Date = (Get-Date).AddYears(-1)
#Logon to Exchange Web Service with default credentials
Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"
$sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
$user = [ADSI]"LDAP://<SID=$sid>"
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList ([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2)
$service.AutodiscoverUrl($user.Properties.mail)
Write-Progress -Activity "Preparing" -Status "Retrieving mailbox list" -PercentComplete 0
#Get Mailboxes for all users in the text file
$Mailboxes = $law | Get-User | Select WindowsEmailAddress, Company
$Count = $Mailboxes.Count
#Go through each users found and process accordingly
ForEach ($Mailbox in $Mailboxes){
$DisplayName = $Mailbox.DisplayName
$i = $i + 1
$pct = $i/$Count * 100
Write-Progress -Activity "Collecting mailbox details" -Status "Processing mailbox $i of $Count - $DisplayName" -PercentComplete $pct
Try {
$Ok = $true
$Mailbox = (Get-Mailbox $mailbox.WindowsEmailAddress -ErrorAction Stop ).PrimarySMTPAddress}
catch [System.Exception]{
$Ok = $false
if ($Ok){
#Set EWS up to impersonationate user
$ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId -ArgumentList ([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress),$Mailbox
$service.ImpersonatedUserId = $ImpersonatedUserId
#Open user folder and bind SentItems folder to the EWS service.
$folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::SentItems,$Mailbox)
$SentFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
#Specify Search Filters: Specify Date and Message Class Type
$Sfir = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsGreaterThanOrEqualTo([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::DateTimeSent, $Date)
$Sfir2 = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::ItemClass, "IPM.Note")
#Add search filters together to form one search
$sfCollection = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+SearchFilterCollection([Microsoft.Exchange.WebServices.Data.LogicalOperator]::AND);
$sfCollection.Add($Sfir)
$sfCollection.Add($Sfir2)
#Create PropertySet to make it possible to retreive all properties of email content
$psPropset = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
$SentItemsview = new-object Microsoft.Exchange.WebServices.Data.ItemView(1000)
$fiItems = $null
#Loop through all all items in 1000 page increment until all items are processed
Do {
#Find Items based on folder Id, search filter and page view
$fiItems = $Service.FindItems($SentFolder.Id,$sfCollection,$SentItemsView)
#Create PropertySet to make it possible to retreive all properties of email content
[Void]$service.LoadPropertiesForItems($fiItems,$psPropset)
#Loop through each email item and retrieve recipients info.
ForEach ($item in $fiItems)
$AllAttendees = $item.ToRecipients | Select -Expand Address
$AllAttendees += $item.CCRecipients | Select -Expand Address
$AllAttendees += $item.BCCRecipients | Select -Expand Address
$sender = $item.From.Address
$subject = $item.Subject
$TimeSent = $item.DateTimeSent
Write-Host "$Sender --- mailbox --- $TimeSent"
for ($index = 0; $index -lt $AllAttendees.count; $index++) {
Write-Progress -Activity "Looping" -Status "Going through all recipients list" -PercentComplete 0
$Attendees = $AllAttendees[$index]
#Filter invalid users, external users and users in Legal department
If ($Attendees -like "*domain.com"){
If ($Law -notcontains $Attendees){
$a = Get-User $Attendees -filter {Company -ne $null} -ErrorAction SilentlyContinue
if ($a){
$Obj = New-Object -TypeName PSObject
$Obj | Add-Member -MemberType NoteProperty -Name Subject -Value $subject
$Obj | Add-Member -MemberType NoteProperty -Name Sender -Value $sender
$Obj | Add-Member -MemberType NoteProperty -Name Sent -Value $TimeSent
$Obj | Add-Member -MemberType NoteProperty -Name Recipients -Value $Attendees
$Report += $Obj
$SentItemsView.Offset += $fiItems.Items.Count
While ($fiItems.MoreAvailable -eq $true)
#Export report to CSV
$Report | Export-Csv "C:\Users\user\Dropbox\Script\LawData.csv" -NoTypeInformation -Encoding UTF8
Tunde

It seems the answer is here:
http://gsexdev.blogspot.com/2011/08/using-allitems-search-folder-from.html.
I'll go through it and let you if successfully.
Thanks
Tunde
Tunde

Similar Messages

  • Using the REST API for files, how do I get information on all the folders and files in a folder?

    I have an app that can successfully get a list of a folders content. However, by default the list is limited to 200 entries. I luckily ran into this limit when getting the list on a folder that contained 226 entries and realized I needed to then request
    a list of the next items but it wasn't obvious from the REST API document how to do that. I tried sending the skipToken query parameter and setting it to 0 initially and incrementing each time I sent the request but always got the same 200 items back. So,
    how do I get the list of files and folders beyond the initial list?

    In SP2013 the skiptoken query parameter does not work with list items. You can look at the link below which discusses using the "__next" parameter.
    http://stackoverflow.com/questions/18964936/using-skip-with-the-sharepoint-2013-rest-api
    Blog | SharePoint Field Notes Dev Tools |
    SPFastDeploy | SPRemoteAPIExplorer

  • How to view all files / folders using a Jtree

    Hello,
    I am developing a 'windows explorer' type application and need to create a JTree which displays all files and folders on a local and remote PC in the same way that windows explorer works.
    Can anyone recommend a good way to read all files / folders and display them in a JTree?
    Thanks in advance!!!!!!

    Can anyone recommend a good way to read all files /
    folders and display them in a JTree? Don't even try to read all the files at once; it could take too long and could consume a lot of memory. Create a JTree model that only reads the children of node when required. I use a simple cache (I hate using a cache but in this case it is needed) to minimise the number of disk reads but I use a TreeExpansionListener to remove items from the cache when a node is about to be collapsed e.g.
        public void treeWillCollapse(TreeExpansionEvent event)
            Object lastElement = event.getPath().getLastPathComponent();
            childCache_.remove(lastElement);
        }

  • Using iPhone to back up/transfer all outlook folders

    Hey all!
    I'm upgrading from Vista to Windows7 and need to transfer my existing Outlook personal folders and calendar. If I sync before the install of Win7, making sure all the correct folders are checked beforehand, then sync again once I've installed Win7, will my Outlook calendar and personal folders transfer to my laptop from my iPhone?
    I'm presuming not, though not sure if I'll be pleasantly surprised?!
    Thanks in advance for any help!

    Peter,
    In the NSS326 under backup, now click on remote replication and you can enable rysnc to alllow backups. Also at the bottom you can create jobs to replicate to another rsync server.
    Thanks,
    Jason Bryant
    Cisco  Support Engineer

  • Get item by it's guid using rest

    Hello everyone,
    for a solution i build for SharePoint 2013 i need to find a specific file using it's guid.
    the szenario is, that i get information about files in sharepoint and save its guid in another system.
    later then, i have to find the file knowing only its guid and its parent web.
    so i need a REST pendant for web.getFileById
    is there a way?
    thanks in advance
    Dennis

    Hi Dennis,
    Per my understanding, you might want to get file by its GUID using REST API.
    As there is no such endpoint in
    REST API can meet you requirement, a workaround is that, you can iterate through the lists/libraries in the current web, then retrieve the GUID property of all the
    files, find the corresponding file with the specific GUID in the retrieved result set, though it is not so elegant as the Web.GetFileById() method provided in Client Object Model.
    Thanks                      
    Patrick Liang
    Forum Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support,
    contact [email protected]
    Patrick Liang
    TechNet Community Support

  • Can't get items created in outlook to sync to my iphone

    Okay I am at a loss for words. I have tried everything even unchecked the do not sync over 30 days button. Nothing in my outlook on my computer will sync / transfer to the iphone. A few things are still there from a sync before I upgraded to the 2.0 version.
    I have checked to make sure all events are the IPM .... status, they are. Anyone have any suggestions??
    Thanks

    What kind of video?  There are dozens of formats, some don't play on a Mac unless you have the right plug-ins for Quicktime.  There are some things you should download to help you out. 
    http://www.telestream.net/flip4mac-wmv/overview.htm
    http://www.videolan.org/vlc/download-macosx.html
    These should cover EVERYTHING you'd ever encounter (though maybe not).  Frankly, if it's not H.264 or w4v (or both), it doesn't belong on your mac. 

  • Use Windows PowerShell to count and list total number of items in Folders E-Mail in Office Outlook?

    I have the need to generate a list of all outlook folders and the total number of items listed beside each folder name. I thought I could simply modify the script from " http://blogs.technet.com/b/heyscriptingguy/archive/2009/01/26/how-do-i-use-windows-powershell-to-work-with-junk-e-mail-in-office-outlook.aspx
    " regarding the total number of items in the junk folder but no luck.
    I thought I could just simply duplicate line 6 of the aforementioned script
    "$folder = $namespace.getDefaultFolder($olFolders::olFolderJunk) " and change the folder name but getting the "Method invocation failed because [Microsoft.Office.Interop.Outlook.OlDefaultFolders] does not contain a method
    named 'olFolder'.
    At line:7 char:1
    + $folder = $namespace.getCurrentFolder($olFolders::olFolder("Design Engineering S ...
    I've found a way to export a list of all these folders using exportoutlookfolders.vbs to a txt file but doesn't include total number of items.
    Looking for any pointers on how to make this work. Don't expect anyone to write it for me but I am still learning PS. Would be great to find a way to import all of these folder and subfolder names into the script. Will be appreciative of any advice though.
    There's an enormous amount of Outlook folders.
    Outlook 2013
    Windows 8
    Thanks,
    Barry

    Since I am not and administrator, but an end user, I do not have access to the Get-Mailxxxx commandlets to make this really easy and had to do this long hand.
      The following will pull folder.name, folder.items.count, and sum the total size of each folder's items for all folders and their subs. 
    Just one warning, the summation can take some time with a large PST file since it needs to read every email in the PST. 
    There is also some minor formatting added to make the results a little more readable.
    $o
    = new-object
    -comobject outlook.application 
    $n
    = $o.GetNamespace("MAPI") 
    $f
    = $n.GetDefaultFolder(6).Parent 
    $i
    = 0
    $folder
    = $f
    # Create a function that can be used and then re used to find your folders
    Function
    Get-Folders()
    {Param($folder)
     foreach($folder
    in $folder.Folders)   
    {$Size =
    0
    $Itemcount
    = 0
    $foldername
    = $folder.name
    #Pull the number of items in the folder
    $folderItemCount
    = $folder.items.count
    #Sum the item (email) sizes up to give the total size of the folder
    foreach ($item
    in $folder.Items)
    {$Itemcount
    = $Itemcount
    + 1
    $Size =
    $Size +
    $item.size
    Write-Progress -Activity ("Toting size of "
    + $foldername
    + " folder.")
    -Status ("Totaling size of "
    + $Itemcount
    + " of "
    + $folderItemCount
    + " emails.")
    -PercentComplete ($itemcount/$folderItemCount*100)
    # just a little formating of the folder name for ease of display
    While($foldername.length
    -le 19){$foldername
    = $foldername
    + " "}
    #Write the results to the window
    Write-Host ("-folder "
    + $foldername
    + "  
    -itemcount " +
    "{0,7:N0}" -f
    $folderItemCount +
    "   -size " +
    "{0,8:N0}" -f ($size/1024)
    + " KB")
    #If the folder has a sub folder then loop threw the Get-Folders function.
    #This two lines of code is what allows you to find all sub folders, and
    #sub sub folders, and sub sub sub for as many times as is needed.
    If($folder.folders.count
    -gt 0)
    {Get-Folders($folder)}
    get-folders($folder)

  • User gets error message when logging into a new pc "Outlook is using anold copy of your .ost"

    We have a user who needs to login to multiple pc's. When she logs into a new pc and opens Outlook she gets the error.
    "Outlook is using an old copy of your Outlook data fuile (.ost). Exit Outlook, delete the file, and restart Outlook. Anew file will automatically be created the next time you initiate a send/receive."
    We manually delete the file and a new one is created but we would like to find a better resolution to this issue. Also we have just recently migrated to O365. any help with finding a better resolution would be appreciated. Thanks.

    Hi,
    I'm marking the reply as answer as there has been no update for a couple of days.
    If you come back to find it doesn't work for you, please reply to us and unmark the answer.
    Best Regards,
    Steve Fan
    Forum Support
    Come back and mark the replies as answers if they help and unmark them if they provide no help.
    If you have any feedback on our support, please click
    here

  • Using Outlook (2010 & 2013) to connect to Exchange using EWS

    First things first.
    I know that Outlook on the PC platform uses MAPI to connect to Excahnge while the Mac flavor of Outlook uses EWS, however, i was cycling through some available EX and ExO PowerShell cmdlets and found a parameter for set-casmailbox named EWSAllowOutlook Which
    leads me to believe that configuring this setting should allow Outlook to use EWS to connect to Exchange. (This is a separate parameter from EWSAllowMacOutlook).
    I tried a manual configuration (entering in the EWS url and setting the correct Outlook Anywhere settings) with no success.
    I also tried manual configuration of an outlook.com and activesync account and entering the EWS URL as well with no success.
    Has anyone successfully configured Outlook for PC to connect to Exchange using EWS and how did you configure the client?
    Thanks

    Hi,
    Sorry for the late reply.
    About the EWSAllowOutlook parameter, I have something to clarify.
    This parameter allow or disallow Outlook 2007 to access EWS for the user.
    Outlook uses EWS for free/buzy, OOF settings, and calendar sharing.
    Outlook connect to Exchange server by using MAPI is a by design behavior.
    We cannot change this.
    Hope it is helpful
    Thanks
    Mavis
    Mavis Huang
    TechNet Community Support

  • How can get all the components used on the current page

    how can I get list of all components being used on the current page using javascript. I have tried CQ.WCM.getComponentList(CQ.WCM.getPagePath()) but this seems to list all the components available.
    Environment CQ 5.5 Update 1, Widnows 7

    You have to remember that once you are in JS, you are only really able to retrieve markup or representations of the DOM.  The markup is the result of a combination of components, which is technically a "server only" concept.  Components are just a way for CQ to organize executable code, so once a page is rendered a component isn't really a thing.  The closest thing I can think of is to list all of the DIVs that represent a component wrapper that are on the page, but this is error prone and clunky.  You could also make AJAX calls back to the server to retrieve a list of the components by node name, but that approach would not return synthetic resources (ones that render, but do not have a node representing them).
    Why are you trying to do this?  Maybe someone has a better idea, but this has a bad smell to me.

  • Excluding public folders when enumerating Outlook folders

    I have an Outlook plugin that searches all Outlook folders for certain information.
    However, some users have been complaining that the plugin searches public folders as well, which are huge in certain corporations, and that in turn makes the search very slow.
    I now use the following mechanism to search Outlook folders:
    NameSpace nameSpace = outlookApp.GetNamespace("MAPI");
    Folders accountFolders = nameSpace.Folders;
    try
    if (nameSpace == null || accountFolders == null)
    return null;
    for (int i = 1; i <= accountFolders.Count; i++)
    MAPIFolder accountFolder = accountFolders.Item(i);
    MailItem res = null;
    try
    res = ScanFolder(accountFolder, mailId, scanUI);
    finally
    if (accountFolder != null) Marshal.ReleaseComObject(accountFolder);
    if (res != null) return res;
    return null;
    finally
    if (accountFolders != null) Marshal.ReleaseComObject(accountFolders);
    if (nameSpace != null) Marshal.ReleaseComObject(nameSpace);
    I've tried to look at the MAPIFolder object, but I didn't find any flag that could help me distinguish standard folders from public folders. Is there a way to do that?
    Thanks,
    Jan

    Read the PR_MDB_PROVIDER property (DASL name http://schemas.microsoft.com/mapi/proptag/0x34140102) using MAPIFolder.PropertyAccessor.GetProperty, convert it to hex using MAPIFolder.PropertyAccessor.BinaryToString. For the PF store objects,
    PR_MDB_PROVIDER property will be pbExchangeProviderPublicGuid (78B2FA70AFF711CD9BC800AA002FC45A) - you can see that property (and others) in
    OutlookSpy: click IMAPIFolder button.
    Dmitry Streblechenko (MVP)
    http://www.dimastr.com/redemption
    Redemption - what the Outlook
    Object Model should have been
    Version 5.5 is now available!

  • How to get registry key lastwritetime using batch/powershell

    Hello,
    I want to get a registry key's LastWriteTime using batch/powershell.  These are what i have tried..
    1. Launch regedit and manually export the key using the UI, this gives me the lastwritetime, but I need a commandline version of this.  regedit /e only exports the key and value data.
    2. dir HKLM:\software\mykey
    nothing returned
    3. Get-ChildItem HKLM:\software\mykey |  Select-Object *
    nothing returned
    4. Get-ItemProperty HKLM:\software\mykey | Select-Object *
    LastWriteTime not returned; other values are returned
    5. (Get-Item HKLM:\software\mykey).LastWriteTime
    Nothing is returned
    Is the only way to do this by using pinvoke with RegQueryInfoKey? 
    Thanks in advance
    ss883r

    The
    .zip on the repository will still work for version 2. Basically, you'll get a definition for a function called 'Add-RegKeyMember'. You can dot source the provided script, or you can copy the function definition into your own script. You would use it like
    this:
    # Using Get-Item:
    PS> Get-Item HKLM:\SOFTWARE | Add-RegKeyMember | select Name, LastWriteTime, ClassName  
    # Using Get-ChildItem:
    PS> Get-ChildItem HKLM:\SOFTWARE | Add-RegKeyMember | select Name, LastWriteTime, ClassName  
    # Passing a path:
    PS> Add-RegKeyMember HKLM:\SOFTWARE | select Name, LastWriteTime, ClassName
    There's also a proxy function for Get-ChildItem that will automatically add the property anytime you use Get-ChildItem (dir, ls, gci) on a registry path. The PSv3 only method I was talking about simply updates the type data to automatically call the function
    on any RegistryKey object. You can actually set version 2 up to do that, but it requires an XML file.

  • How To Get Deleted Item Count and Associated Item Count And LastLogOn and LogOff Time For A Mailbox In Exchange Using EWS

    Using Powershell cmdlet i get  all the details..But i want to get these Details by using EWS Managed Api.Is It Possible to do???
    Powershell Cmdlet,
    Get-MailboxStatistics -Identity Username, Using this cmdlets all the details will get displayed.
    DeletedItemCount:5 //Here how this count comes.In My OutlookWebApp the deleteditems folder contains 13 items in it..But the count shows only 5.
    TotalDeletedItemSize:5.465 Kb//Even this value too does not match with DeletedItems Folder size in owa.
    AssociatedItemCount:12
    LastLogOnTime:11/11/11 12:43PM
    LastLogOff Time:11/11/11 2:43PM
    In EWS,
    By Looping through all folders i can get the total item count and total item size.Even i can get deleteditems  count .But that value does not match  With the powershell value.Even the TotalDeletedItemSize
    Doesnt match.
    Using EWS Managed Api ,Looping through folders i can get ItemCount,TotalitemSize,(DeletedItems,TotalDeleteditemSize(These TwoValues Does not match with values comes from powershell))
    Now how to get the Associated item count and lastlogoff and logon time using EWS managed Api.Is it Possible???
    And even y the deleteditems count and size values varies between EWS and powershell.

    What happens if you execute the below code?
    Get-MailboxFolderStatistics [email protected] | where {$_.FolderPath -like "/Deleted Items"}
    Refer this blog. You may get some dice
    http://exchangepedia.com/blog/2008/09/configuring-deleted-item-retention.html
    Regards Chen V [MCTS SharePoint 2010]

  • My sent messages in outlook for mac suddenly stopped syncing with my iPhone and iPad, all other folders work correctly. How can I get them to start syncing again?

    My sent messages in outlook for mac suddenly stopped syncing with my iPhone and iPad, all other folders work correctly. How can I get them to start syncing again?

    You can disable the Adobe Reader plugin in Firefox (Tools > Add-ons > Plugins) and use the external Adobe Reader application or Preview application instead.
    *Firefox > Preferences > Applications > Adobe PDF document : Use Adobe Reader
    PDF files may also be found under another entry like Portable document.
    *https://support.mozilla.org/kb/change-firefox-behavior-when-open-file

  • Trying to delete file from trash but get this: The operation can't be completed because the item "File name" is in use. All other files delete except this one. Please help

    Trying to delete file from trash but get this: The operation can’t be completed because the item “File name” is in use. All other files delete except this one. Please help

    Maybe some help here:
    http://osxdaily.com/2012/07/19/force-empty-trash-in-mac-os-x-when-file-is-locked -or-in-use//

Maybe you are looking for

  • Need  ABAP coding in  Proxy TO File scenario

    Hi friends,   i need  to do the  Proxy to file scenario.. for this.. i want to retrive the data from R/3 system and  load the data into the class which we defined in SPROXY  (Outbound  class) .. so, can any one give me the exact coding... for this..

  • Problem while sending multiple messages to JDBC

    hi I am trying to run a scenario file to jdbc(multiple). Inserting row into table with the file details and updating the same row. I created 2 message mapping and 2 operation mapping. One mapping to insert row and second to updated the same row. In I

  • Web services and RMI

    Hi, I have a question about the scalability of RMI with Oracle JVM. What we intend to do is have about 10 SOAP webservices all interacting with our Oracle 8i instance. One of the developers suggestion is to use the Sun Java/SOAP Toolkit to make the W

  • Oracle Lite: How to create data subsetting parameters?

    I need to know: how to create data subsetting parameters? I need these parameters for use of a restricting predicate in an item publication. I were looking the forum and i found topics about "how to set?" but i don't found how to create a data subset

  • How to install Win7 on Satellite C870-190?

    Hi, I hope I post in the right forum category so... My laptop is Toshiba Satellite C870-190 and it doesnt want to boot my windows 7 CD. I tried first with DEL button which open the boot system when I start the notebook and then chose the CD-ROM devic