title: How to export mail message to EML or MSG file with PowerShell and EWS
body: <p>I'm currently working on a PowerShell script that need to extract all mail messages from a specific mailbox as .eml or .msg files and save them on a backup server. I'm using powershell version 5 with the Exchange 2010 management console module (EWS).</p>
  
  <p>Currently, my script is able to access all messages in the inbox folder with their properties such as Body, Subject, attachments and so on. However, I couldn't find an easy way or method to export the messages (with their attachment(s)). So my question is, does EWS in Exchange 2010 provide a method to extract/save a message from a mailbox?</p>
  
  <p>Here's my script:</p>
  
  <pre><code>add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
  
  $dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"
  [void][Reflection.Assembly]::LoadFile($dllpath)
  $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)
  $windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
  $sidbind = "LDAP://&lt;SID=" + $windowsIdentity.user.Value.ToString() + "&gt;"
  $aceuser = [ADSI]$sidbind
  $service.AutodiscoverUrl($aceuser.mail.ToString())
  
  $MailboxName = get-mailbox -Identity myMailBox@myWorkPlace.com
  
  $folderidcnt = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName.PrimarySmtpAddress.ToString())
  $rootfolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service, $folderidcnt)
  
  
  $offset = 0;
  $view = new-object Microsoft.Exchange.WebServices.Data.ItemView(10000, $offset)
  
  $response = $service.LoadPropertiesForItems($results, [Microsoft.Exchange.WebServices.Data.PropertySet]::FirstClassProperties)
  
  foreach ($mail in $results){
  
  if ($mail.ToString() -eq "Microsoft.Exchange.WebServices.Data.EmailMessage"{
      **"Function to export this message an an .eml or .msg file on a remote shared folder"**
       }
  }
  </code></pre>