title: Save all attachments from mail
body: <p>I have a script that is supposed to download all attachments from "Inbox" then move them to another folder named "Processed". I filter mails by subject. If exist then download all attachments and move the mails.
  For example I have 5 mails with attachments (xls) the subject are named like:</p>
  
  <pre>
  BB_asd_green_dsa
  AD_acv_blue_sf
  FD__c_d_red_sa
  CV_saas_white_sdsd
  as_dc_asa_purple
  </pre>
  
  <p>When I start the script it saves 3 attachments, the mails with attachments are moved too. And then it stops.</p>
  
  <p>Second start. It saves 1 attachment &amp; moves 1 mail</p>
  
  <p>And one last manual start script saves the last attachment and moves the mail.</p>
  
  <p>For what reason doesn't the script save and move all attachments with their mails?</p>
  
  <p>Here is the script:</p>
  
  <pre class="lang-cs prettyprint-override"><code>$olFolderInbox = 6
  $outlook = New-Object -Com Outlook.Application;
  
  $ns = $outlook.GetNameSpace("MAPI");
  #$ns.Logon("Outlook")
  #$ns.SendAndReceive($true)
  #Start-Sleep -s 0
  $inbox = $ns.GetDefaultFolder($olFolderInbox)
  $messages = $inbox.Items
  Write-Host $messages.Count
  foreach ($message in $messages) {
      $msubject = $message.Subject
      $b = $msubject.Filename
  
      $filepath = "D:\Users\h.yordanov\Desktop\convertexltohtm\xls\"
      $message.Attachments | foreach{
          Write-Host $message.Filename
          $a = $_.Filename
          $msubject = $message.Subject
          $msubjectW = $msubject -replace '[^0-9]', ''
          $b = $msubjectW + ".xls"
          if ($msubject.Contains("green") -or $msubject.Contains("blue") -or $msubject.Contains("green") -or $msubject.Contains("white") -or $msubject.Contains("purple")) {
              $_.SaveAsFile((Join-Path $filepath $b))
          }
      }
  
      $MoveTarget = $inbox.Folders.Item("Processed")
      [void]$message.Move($MoveTarget)
  }
  </code></pre>
  
  <p>I used this script to move the mails, but still not all 5 mails are moved at once:</p>
  
  <pre><code>    $Date = [DateTime]::Now.AddDays(-180)
  
  $Last6Months =  $Date.tostring("MM/dd/yyyy")
  
  
  $o = New-Object -comobject outlook.application
  $n = $o.GetNamespace(“MAPI”)
  
  
  
  $Account = $n.Folders | ? { $_.Name -eq 'h.yordanov@sample.com' };
  $Inbox = $Account.Folders | ? { $_.Name -match 'Inbox' };
  $TargetFolder = $Inbox.Folders.Item('Processed')
  
  
  $Inbox.Items |
  Where-Object -FilterScript {
      $_.senton -ge "$Last6Months"  
  }  |
  ForEach-Object -Process {
      [void]$psitem.Move($TargetFolder)
  }
  </code></pre>
  
  <p>Btw i am using MS office Pro plus 2010 64-bit</p>