Office 365 script to move emails from .csv? RRS feed

  • Question

  • I'm trying to make a script that moves emails from one folder to another, in the .csv file I have subject in column 1, and date sent in column 2.

    I made this so far, but it only deletes the files, and doesn't take it from a csv.

    Get-RoleGroupMember -Identity "Discovery Management"
    Add-RoleGroupMember -Identity "Discovery Management" -Member email@yourdomain.onmicrosoft.com
    New-RoleGroup "Mailbox Import-Export Management" -Roles "Mailbox Import Export"
    Add-RoleGroupMember "Mailbox Import-Export Management" -Member email@yourdomain.onmicrosoft.com
    Get-Mailbox -ResultSize Unlimited | Search-Mailbox -SearchQuery {Subject:"subject" AND Sent:"5/12/2011"} -DeleteContent -LogLevel Full SearchDumpster

    I also have this script, but again it only moves in BULK, and not 1 single email at a time out of csv.

    param (
    [Parameter(Position=0,Mandatory=$True,HelpMessage="Specifies the mailbox to be accessed")]

    [Parameter(Position=1,Mandatory=$True,HelpMessage="Source folder (from which to move messages)")]

    [Parameter(Position=2,Mandatory=$False,HelpMessage="is the Source folder primary or archive?")]

    [Parameter(Position=3,Mandatory=$True,HelpMessage="Target folder (messages will be moved here)")]

    [Parameter(Position=4,Mandatory=$False,HelpMessage="is the target folder primary or archive")]

    [Parameter(Position=5,Mandatory=$False,HelpMessage="Admin Username with impersonation permission")]

    [Parameter(Position=6,Mandatory=$False,HelpMessage="Admin Password")]


    [string]$warning = "Yellow"                      # Color for warning messages
    [string]$error = "Red"                           # Color for error messages
    [string]$LogFile = "C:\Temp\Log.txt"             # Path of the Log File

    $icount = 0;
    $FolderId = @();
    $FolderName = "$SourceFolder","$TargetFolder"
    $Location = "$SourceType","$TargetType"

    #if username or password are empty, ask for both
    if ([string]::IsNullOrEmpty($username) -or [string]::IsNullOrEmpty($password)) {
        $p = get-credential -Message "Admin Username and password with impersonation permission"
        if ($p) {
            $username = $p.UserName
            $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($p.Password)
            $Password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
        else { 
                Write-Error "Admin credential needed"
                return $False

    # Make sure the Import-Module command matches the Microsoft.Exchange.WebServices.dll location of EWS Managed API, chosen during the installation
    Import-Module -Name "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"

    #Creating the Exchange service object
    $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList Exchange2013_SP1

    #Provide the credentials of the O365 account that has impersonation rights on the mailbox $MailboxName
    $service.Credentials = new-object Microsoft.Exchange.WebServices.Data.WebCredentials -ArgumentList $username, $password

    #Exchange Online URL
    $service.Url= new-object Uri("https://outlook.office365.com/EWS/Exchange.asmx")

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

    While ($i -lt 2)
        if ($Location[$i] -eq 'primary')
            $FolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(100)
            $FolderView.Traversal = [Microsoft.Exchange.Webservices.Data.FolderTraversal]::Deep
            $SearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,$FolderName[$i])
            $FindFolderResults = $service.FindFolders([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$SearchFilter,$FolderView)

                Write-host "The folder" $FolderName[$i] "was successfully found in the primary mailbox" -ForegroundColor $warning
                $FolderId += $FindFolderResults.Id
                Write-host "The folder" $FolderName[$i] "was not found in the primary mailbox" -ForegroundColor $warning; $i++; continue;
            $Mbx = (Get-Mailbox $MailboxName)
            if ($Mbx.ArchiveStatus -eq 'Active')
                (Get-MailboxFolderStatistics $guid).Name | % { $j++;
                    if ($FolderName[$i] -match $_) {
                        Write-host "The folder" $FolderName[$i] "was successfully found in the archive mailbox" -ForegroundColor $warning
                        $AFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(100)
                        $AFolderView.Traversal = [Microsoft.Exchange.Webservices.Data.FolderTraversal]::Deep
                        $ASearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,$FolderName[$i])
                        $AFindFolderResults = $service.FindFolders([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::ArchiveMsgFolderRoot,$ASearchFilter,$AFolderView)
                        $FolderId += $AFindFolderResults.Id
                        if ($j -eq (Get-MailboxFolderStatistics $guid).Count) 
                            Write-Host "All the archive folders have been checked and" $FolderName[$i] "was not found" -ForegroundColor $warning; $i++; continue;
            else { Write-host "The archive mailbox is not enabled." -ForegroundColor $warning; $i++; continue; }

    if($FolderId.Count -eq 2)  {
        $ItemView = new-object Microsoft.Exchange.WebServices.Data.ItemView(1000)
        $icount = 1
            $FindItemResults = $service.FindItems($FolderId[0],$ItemView)
            write-host $FindItemResults.TotalCount "items have been found in the Source folder and will be moved to the Target folder."
            foreach ($Item in $FindItemResults.Items)
                $Message = [Microsoft.Exchange.WebServices.Data.EmailMessage]::Bind($service,$Item.Id)
                $Message.Move($FolderId[1]) > $null

                if (($icount % 100) -gt 0) { write-host "." -NoNewline }
                else { write-host "$icount" }
                $icount += 1

            $ItemView.offset += $FindItemResults.Items.Count

        }while($FindItemResults.MoreAvailable -eq $true)

        if (($icount % 100) -gt 0) { write-host ($icount-1) }
        Write-host "Check the source and the target folders. One of them is probably invalid." -ForegroundColor $error 

    #Catch the errors
    trap [System.Exception]
         Write-host ("Error: " + $_.Exception.Message) -foregroundcolor $error;
         Add-Content $LogFile ("Error: " + $_.Exception.Message);

    Saturday, February 3, 2018 12:22 AM

All replies

  • We don't fix scripts fond on the Internet.  You need to learn the CmdLets and technology and post back with a question about a script you are writing.  Blindly copying scripts from the Internet is a very dangerous practice.  Of course the fist script deletes only.  That is what the CmdLet used has been told to do.

    Use help to learn CmdLets.  Search for MS and other tutorials on the technology.

    Please carefully review the following to set your expectation of technical forums.

    This Forum is for Scripting Question Rather than script requests

    Script Gallery.

    Learn PowerShell  

    Script requests


    Saturday, February 3, 2018 12:49 AM