Steve
Steve

Reputation: 59

Calling a VB Script from a Powershell script produces unexpected runtime errors when sending automated emails

I have the following VB Script:

Set MSOutlook = CreateObject("Outlook.Application")
Set MailMsg = MSOutlook.CreateItem(0)

With MailMsg            
        .To = "[email protected]"
        .Subject = "my subject"
        .HTMLBody = "my text"
        .Display
        SendKeys "{TAB}{DOWN}{DOWN}{ENTER}", True
        .Send
End With

Set MSOutlook = Nothing
Set MailMsg = Nothing

This script runs fine when executed within a VB compiler, such as Microsoft Visual Basic for Applications.

The SendKeys is required because of this damn Titus classification system we have in place at work to classify everything, such as emails and documents.

The email sends fine and it is classified correctly.

Now I am trying to call this script from the following Powershell script:

& cscript 'C:\Documents\sendEmail.vbs' //nologo

But the following error is received either in the Powershell ISE or when calling the vb script directly from a PowerShell console:

cscript.exe : C:\Documents\sendEmail.vbs Microsoft VBScript runtime error: Type mismatch: 'SendKeys'

Anyone know much about this and why the SendKeys function apparently cannot be used this way?

To pre-empt comments, yes, I would really like to move this vb functionality into the PowerShell script but the TITUS plugin is causing all sorts of headaches around that right now.

Thanks

Upvotes: 1

Views: 174

Answers (1)

Heinzi
Heinzi

Reputation: 172390

In VBA, the SendKeys command is a member of the global Interaction module and, thus, always in scope.

In VBScript, you need to use the SendKeys method of the WScript.Shell object instead:

Dim shell
Set shell = CreateObject("WScript.Shell")
shell.SendKeys "{TAB}{DOWN}{DOWN}{ENTER}", True

Upvotes: 3

Related Questions