0

how can I run this powershell script as a Windows Service?

$olSaveType = "Microsoft.Office.Interop.Outlook.OlSaveAsType" -as [type] 

Add-Type -Assembly "Microsoft.Office.Interop.Outlook" $Outlook =
New-Object -ComObject Outlook.Application $Namespace =
$Outlook.GetNameSpace("MAPI") 

$EmailsInFolder= $NameSpace.GetDefaultFolder(6).Folders.Items
$EmailsInFolder | ft SentOn, Subject, Sensitivity -AutoSize -Wrap

foreach ($EmailInFolder in $EmailsInFolder)        
{
   $EmailInFolder.Subject = "Test" 
   $EmailInFolder.Save()
}

I like to change the email subject when I move the email in a folder.

Regards Stefan

2
  • 1
    I'm no Office dev expert, but surely there is a way to program Outlook to do this? Some kind of rule or macro? Seems very heavy-handed having a system service to manage your email for you, especially one written in a language not designed for that type of development. Commented Oct 20, 2019 at 22:25
  • To add to @boxdog's comment: Using the COM-based Automation libraries isn't supported in Window services - see support.microsoft.com/en-us/help/257757/… Commented Oct 21, 2019 at 3:14

2 Answers 2

1

Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.

If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution.

Read more about that in the Considerations for server-side Automation of Office article.

As a workaround, you may consider using a low-level API on which Outlook is based on - Extended MAPI or any other wrapper around that API such as Redemption.

Or, if you deal with Exchange profiles only, you may consider using EWS, see Start using web services in Exchange for more information.

Sign up to request clarification or add additional context in comments.

Comments

0

Firstly, you cannot use Outlook (or any other Office app) from a service. Secondly, an Outlook COM addin might be a better solution - it always runs when Outlook is running, so there is no need for a Windows service.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.