2017-03-20 22 views
0

Exchange 2010에서 특정 계정의받은 편지함에있는 모든 메시지를 내보내려고합니다.이 솔루션은 매우 유용하지만 다른 게시물 How to export mail message to EML or MSG file with PowerShell and EWS에 있지만 스크립트를 실행하는 중에 오류가 발생했습니다. 나는 EWS를 처음 사용하는데 약간의 상실감이있다.PowerShell 및 EWS 파트 2를 사용하여 EML 또는 MSG 파일로 메일 메시지를 내보내는 방법

add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010 

$strMailboxName = "[email protected]" 
$strSaveLocation = "\\server\share" 

$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://<SID=" + $windowsIdentity.user.Value.ToString() + ">" 
$aceuser = [ADSI]$sidbind 
$service.AutodiscoverUrl($aceuser.mail.ToString()) 

$MailboxName = get-mailbox -Identity $strMailboxName 

$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") { 
    $mailSubject = $mail.Subject 
    $mailProps = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.ItemSchema]::MimeContent) 
    $mail.Load($mailProps) 
    #TODO: clean up $mailSubject so it's filesystem friendly 
    $fStream = New-Object System.IO.FileStream("$strSaveLocatoin\$mailSubject.eml", [System.IO.FileMode]::Create) 
    $fStream.Write($mail.MimeContent.Content, 0, $mail.MimeContent.Content.Length) 
    $fStream.Close() 
} 
} 

나는 다음과 같은 오류가 점점 오전 : 나는의 시작 부분에 2 $ STR 변수를 annonymized 한

Exception calling "LoadPropertiesForItems" with "2" argument(s): "Value cannot be null. 
Parameter name: items" 
At C:\PowershellScripts\Exchange-SaveEMailAsFile.ps1:23 char:44 
+ $response = $service.LoadPropertiesForItems <<<< ($results, [Microsoft.Exchange.WebServices.Data.PropertySet]::FirstC 
lassProperties) 
    + CategoryInfo   : NotSpecified: (:) [], MethodInvocationException 
    + FullyQualifiedErrorId : DotNetMethodException 

You cannot call a method on a null-valued expression. 
At C:\PowershellScripts\Exchange-SaveEMailAsFile.ps1:27 char:19 
+ if ($mail.ToString <<<<() -eq "Microsoft.Exchange.WebServices.Data.EmailMessage") { 
    + CategoryInfo   : InvalidOperation: (ToString:String) [], RuntimeException 
    + FullyQualifiedErrorId : InvokeMethodOnNull 

을 여기

내가 현재 사용하고있는 코드의 복사본입니다 스크립트를 제외하고 코드는 제가 게시 한 것입니다.

원래 게시물에 댓글을 추가하고 싶지만 아직 충분한 평판을 얻지 못했습니다.

도움을 주시면 감사하겠습니다. 고맙습니다.

+0

오류와 코드가 정확하게 일치하지 않습니다. 당신은 당신의 코드에서'$ 결과'를 볼 수있는'$ view'를 가지고 있습니다. – Matt

+0

죄송합니다. 다른 실행 결과를 게시했습니다. 나는 그것이 어떤 차이를 만들 었는지 알기 위해 몇 가지 변수를 돌아 다니고있었습니다. 원래의 게시물을 올바른 오류 메시지와 함께 편집했습니다. 내 사과. – BomSquad

+0

Ok .. 그래서'$ results'는 값을 가지지 않으므로 오류가 발생합니다. 아직도 변수가 섞여 있다고 생각합니다. – Matt

답변

0

LoadPropertiesForItems 전달 된 첫 번째 변수에는 해당 항목 개체가 포함되어 있고 $result은 해당 코드에 채워지지 않아서 오류가 발생합니다. MSDN blog에서 예를 볼 수 있습니다.

나는 Exchange 서비스에 연결된 사서함의받은 편지함에서 각 메일을 $exchangeService으로 가져 오는 데 필요한 다음 테스트를 수행했습니다. 코드와 일치하도록이 코드에서 여러 변수를 변경해야합니다. 이것은 의도적으로 이루어 졌기 때문에 사물이 어떻게 작용 하는지를 볼 수 있습니다.

이 코드는 내 경험이 제한적일 수 있으므로 더 좋을 수도 있습니다. 그것은 어려운 일이 아니며 좋은 테스트를 위해해야 ​​할 필요가 있기 때문에이 주석을 몇 가지 정규식으로 해결했습니다. #TODO : $ mailSubject를 정리하면 파일 시스템에 친숙합니다.. 한 가지가 이 아니라이 여기에 완료되면 빈 제목이있는 파일을 설명하는 논리입니다. 현재 그들은 서로를 덮어 쓰며 처리 된 것과 같은 마지막 ".eml"파일 하나로 끝납니다.

# Folder that will contain the eml files. 
$destinationFolder = "E:\temp\test" 

# Create the view. Set for 1000 paged items 
$pageSize = 1000 
$itemView = [Microsoft.Exchange.WebServices.Data.ItemView]::New($pageSize) 
$itemView.PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties) 
$mimeView = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.ItemSchema]::MimeContent) 

# Bind to the root folder 
$rootFolderID = New-Object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox) 
$boundRootFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($exchangeService,$rootFolderID) 

# regex to remove illegal characters in the subject that are not allowed in the ntfs file system 
$regex = ([char[]]'<>:"/\|?*' | ForEach-Object{[regex]::Escape($_)})-join"|" 

# Loop through paging results 
do{ 
    # Get the next batch of results 
    $filterResults = $boundRootFolder.FindItems($itemView) 

    # We need to process each mail in this set of results 
    $filterResults.Items | ForEach-Object{ 
     # Get the subject before we change the view 
     $mailSubject = $_.Subject -replace $regex 

     # Load the properties for the view create earlier 
     $_.Load($mimeView) 

     # Using a file stream to export this single messages mime content 
     write-host "$destinationFolder\$mailSubject.eml" -ForegroundColor Green 
     $stream = New-Object System.IO.FileStream("$destinationFolder\$mailSubject.eml", [System.IO.FileMode]::Create) 
     $stream.Write($_.MimeContent.Content, 0, $_.MimeContent.Content.Length) 
     $stream.Close() 
    } 

    # Loop if there are still more results in the filter. Adjust the filter offset. 
    $itemView.Offset += $filterResults.Items.Count 
} while($filterResults.MoreAvailable) 

내 첫 번째 문제는 내가 같은 시간에 필요한 속성을로드 할 수 있어야하지만, 따라서 두 개의로드 작업이 기술적으로이 있다는 것을 어떻게 알 수 없다는 것입니다. 처음에는 처음에 찾아 루프에서 다시 한번 MIME 콘텐츠를 얻습니다. 이것은 당신이 오류를

The property MimeContent can't be used in FindItem requests. 

를 얻을 한 번에 모든 것을하려고 노력 만약 내가 Glen's blog on the EWS API에서 정말 좋은 모습을 가질 것이기 때문에이 수행되어야하는 방법을 가능성이있다. 좋은 정보가 많이 있습니다. 내가 어려움을 겪을 때 EWS API가 어떻게 작동하는지 확고하게 알게되었습니다. 그는 또한 내가 때때로 보았던 여기의 사용자이기도합니다.

+0

고맙습니다. 블로그를 확인하겠습니다. 도움에 감사드립니다. – BomSquad