Get contents of msg file to string

I use Powershell to parse the contents of email messages that are stored in a local folder.

The code is as follows:

Get-ChildItem "C:\projtest\emails" -Filter *.msg |
ForEach-Object {
    $msg = ""
    $outlook = New-Object -comobject outlook.application
    $msg = $outlook.Session.OpenSharedItem($_.FullName)
    $msg | Select -ExpandProperty body 

    Write-Host $msg
}

$outlook.Quit()

Currently, I just want to open the file, get the contents and display it.

The problem that I encountered is that after running the script OUTLOOK.EXE does not close, so I can not run the script again in the same message.

Is there a better way to open Outlook email messages, get the contents in a line in PowerShell, and close the Outlook process?

+4
source share
1 answer

Do not open or close Outlook, do not open it once, do not do all your work, and do not close it at the end.

$outlook = New-Object -comobject outlook.application
Get-ChildItem "C:\projtest\emails" -Filter *.msg |
    ForEach-Object {
        $msg = $outlook.Session.OpenSharedItem($_.FullName)
        $msg.body 
    }
$outlook.Quit()

: , .msg , Outlook. ForEach:

$outlook = New-Object -comobject outlook.application
Get-ChildItem "C:\projtest\emails" -Filter *.msg |
    ForEach-Object {
        $msg = $outlook.Session.OpenSharedItem($_.FullName)
        $msg.body 
        $msg.Close()
    }
$outlook.Quit()
+4

Source: https://habr.com/ru/post/1675638/


All Articles