Trying to create script to run another script each time I receive a new email

As the title says i'm trying to create a script to run another script each time I receive a new email.

Background: The script that it needs to run is a powershell script (if it could be combined that would be great) but i'm wanting this to alert operators that they have recevied an emergency email. I'm pushing a notification to the app pushover on their phones.

The powershell script that I already have made can be run and does exactly what I want it to do. Sends a request to Pushover's API and then sends the notification to the corresponding smartphones.

I have done some research online and have come up with this script but as I am newer to powershell some the language i'm confused on.

Below is the code I have so far... not sure if it is even in the right direction

$MailboxName = "email@domain.com"
$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"
[void][Reflection.Assembly]::LoadFile($dllpath)
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)
$service.TraceEnabled = $false

$service.Credentials = New-Object System.Net.NetworkCredential("user","password", "domain")
$service.Url="https://abc.local/ews/exchange.asmx"

try{
$fldArray = new-object Microsoft.Exchange.WebServices.Data.FolderId[] 1
$Inboxid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)
$fldArray[0] = $Inboxid
$stmsubscription = $service.SubscribeToStreamingNotifications($fldArray, [Microsoft.Exchange.WebServices.Data.EventType]::NewMail)
$stmConnection = new-object Microsoft.Exchange.WebServices.Data.StreamingSubscriptionConnection($service, 30);
$stmConnection.AddSubscription($stmsubscription)
Register-ObjectEvent -inputObject $stmConnection -eventName "OnNotificationEvent" -Action {

    foreach($notEvent in $event.SourceEventArgs.Events){    
        [String]$itmId = $notEvent.ItemId.UniqueId.ToString()
        $message = [Microsoft.Exchange.WebServices.Data.EmailMessage]::Bind($event.MessageData,$itmId)
        IF ($message.Subject -eq "execprocess"){
            Start-Process  "opsalert.ps1" 
        }            
    }    


} -MessageData $service

}catch [Exception] {
                Get-Date  | Out-File C:\logs\logError.txt -Append
                "Error : "+  $_.Exception.Message  
                }
Register-ObjectEvent -inputObject $stmConnection -eventName "OnDisconnect" -Action {$event.MessageData.Open()} -MessageData $stmConnection
$stmConnection.Open()

Error codes i'm getting:

Register-ObjectEvent : Cannot bind argument to parameter 'InputObject' because it is null.
At C:\home\dustin\IT\Pushover\emailmonitor.ps1:34 char:34
+ Register-ObjectEvent -inputObject <<<<  $stmConnection -eventName "OnDisconnect" -Action {$event.MessageData.Open()}
-MessageData $stmConnection
    + CategoryInfo          : InvalidData: (:) [Register-ObjectEvent], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.RegisterObj
   ectEventCommand

You cannot call a method on a null-valued expression.
At C:\home\dustin\IT\Pushover\emailmonitor.ps1:35 char:20
+ $stmConnection.Open <<<< ()
    + CategoryInfo          : InvalidOperation: (Open:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Help would be very appreciated!

Thanks!

  • Moved by Bill_Stewart Tuesday, November 19, 2013 4:49 AM Moving to more appropriate forum
November 19th, 2013 1:47am

I really don't believe you can remotely event Exchange services. You can install event code into Exchange and assign it to be used.

You would do better to ask this kind of question in the Exchange 2010 Developers forum.

Free Windows Admin Tool Kit Click here and download it now
November 19th, 2013 6:35am

Well if you could help me on the installing event code into Exchange and then assigning it that would be great as well!

Thanks

November 20th, 2013 8:34pm

Well if you could help me on the installing event code into Exchange and then assigning it that would be great as well!

Thanks

I have no idea what you are trying to do. Your question is very vague. You would need to start by defining the purpose for this rather than trying to say how you want to do it.\

It sounds like you want to detect the receipt of emails in Outlook.  If that Is the case you need to use Outlook VBA.  If you are trying to set up detection of email for a whole organization then you need to be even more specific.

Free Windows Admin Tool Kit Click here and download it now
November 20th, 2013 8:42pm

Sorry that I didn't get across what I'm trying to do the first time, I'll try again.

The purpose of this is to run a script (opsalert.ps1) whenever abc@local.com receives an email, opsalert.ps1 is already made. I want to have this automated and without the use of an outlook client being open all of the time.

That's a short explanation but I think it gets what i'm trying to do across, let me know if you need more info.

Thanks, I appreciate it greatly!

November 20th, 2013 8:49pm

Sorry - that cannot be done.  PowerShell has no access to Outlook messaging without running Outlook.

You can use EWS if you have it set up and you are running  Exchange 2010 or later.  It will have to continually scan.

Outlook can execute a rule that runs a scipt or macro on the receipt of email.

Free Windows Admin Tool Kit Click here and download it now
November 20th, 2013 9:09pm

Yes that's what i'm trying to do, I guess I didn't say EWS, but I have that installed and and am running Exchange 2010
November 20th, 2013 9:12pm

In your initial code - where did you find it?  The events you see are only defined on the connection object.  I don't remember that there are events on  the connection that alert on mail receipt. 

Try posting that question in the Exchange forum.  If the event is exposed then you can probably access it in PowerShell.

You can also just look it up in the API.

Free Windows Admin Tool Kit Click here and download it now
November 20th, 2013 9:12pm

It wont let me post the link, but I found it on stack over flow, if you google this "$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll" [void][Reflection.Assembly]::LoadFile($dllpath)" It is the third link

And I think a mod moved this to the Exchange forum already

November 20th, 2013 9:18pm

It wont let me post the link, but I found it on stack over flow, if you google this "$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll" [void][Reflection.Assembly]::LoadFile($dllpath)" It is the third link

And I think a mod moved this to the Exchange forum already

Yes - you are in Exchange development. 

What is the event (if ther eis one) for new mail arrival when connected with EWS? 

Like I posted.  I don't think this exists.

Free Windows Admin Tool Kit Click here and download it now
November 20th, 2013 9:21pm

Ok I see it.  I will have to set it up when I get back.  It looks like the code should work.

What issue are you having with it?

Check this object to see why it is coming up null: $stmConnection

November 20th, 2013 9:26pm


What issue are you having with it?

Check this object to see why it is coming up null: $stmConnection


Thats great to hear, and thanks for checking into it! I posted the errors I got back, and i'm sorry that I don't know enough yet to "check the object" I'm not sure why it is coming up null. Servers haven't been rebooted since EWS install, and I haven't really done any setting up of the EWS, not sure if either of those would affect it.

Thanks!

Free Windows Admin Tool Kit Click here and download it now
November 20th, 2013 9:35pm

It is likely that this doesn't cause an error so it needs to be checked for null. It will be null if you cannot authenticate,

$stmsubscription = $service.SubscribeToStreamingNotifications($fldArray, [Microsoft.Exchange.WebServices.Data.EventType]::NewMail)

if(-not $stmsubscription ){
      Write-Host "Connection failed"  
}else{
    # continue with connection.

   ....
November 20th, 2013 10:13pm

I added that to my original script to come up with this 

$MailboxName = "email@domain.com"
$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"
[void][Reflection.Assembly]::LoadFile($dllpath)
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)
$service.TraceEnabled = $false

$service.Credentials = New-Object System.Net.NetworkCredential("user","password", "domain")
$service.Url="https://abc.local/ews/exchange.asmx"

try{
$fldArray = new-object Microsoft.Exchange.WebServices.Data.FolderId[] 1
$Inboxid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)
$fldArray[0] = $Inboxid
$stmsubscription = $service.SubscribeToStreamingNotifications($fldArray, [Microsoft.Exchange.WebServices.Data.EventType]::NewMail)

if(-not $stmsubscription ){
      Write-Host "Connection failed"  
}else{
    # continue with connection.
$stmConnection = new-object Microsoft.Exchange.WebServices.Data.StreamingSubscriptionConnection($service, 30);
$stmConnection.AddSubscription($stmsubscription)
Register-ObjectEvent -inputObject $stmConnection -eventName "OnNotificationEvent" -Action {

    foreach($notEvent in $event.SourceEventArgs.Events){    
        [String]$itmId = $notEvent.ItemId.UniqueId.ToString()
        $message = [Microsoft.Exchange.WebServices.Data.EmailMessage]::Bind($event.MessageData,$itmId)
        IF ($message.Subject -eq "execprocess"){
            Start-Process  "opsalert.ps1" 
        }            
    }    


} -MessageData $service

}catch [Exception] {
                Get-Date  | Out-File C:\logs\logError.txt -Append
                "Error : "+  $_.Exception.Message  
                }
Register-ObjectEvent -inputObject $stmConnection -eventName "OnDisconnect" -Action {$event.MessageData.Open()} -MessageData $stmConnection
$stmConnection.Open()

I have another error after executing it with the changes

Missing closing '}' in statement block.
At C:\home\dustin\IT\Pushover\emailmonitor.ps1:40 char:22
+ $stmConnection.Open() <<<<
    + CategoryInfo          : ParserError: (CloseBraceToken:TokenId) [], ParseException
    + FullyQualifiedErrorId : MissingEndCurlyBrace

Free Windows Admin Tool Kit Click here and download it now
November 20th, 2013 11:14pm

I am running it now.  Works good but I need to create a proper script to call.  Right now it just events.

November 20th, 2013 11:27pm

I am running it now.  Works good but I need to create a proper script to call.  Right now it just events.

Free Windows Admin Tool Kit Click here and download it now
November 20th, 2013 11:42pm

You cannot directly call a powershell script.  It has to be run like this:

Start-Process -FilePath 'powershell' -ArgumentList '-FilePath c:\scripts\opsalert.ps1'

November 21st, 2013 12:47am

Ok I made that change, but i'm still getting the error

Missing closing '}' in statement block.
At C:\home\dustin\IT\Pushover\emailmonitor.ps1:40 char:22
+ $stmConnection.Open() <<<<
    + CategoryInfo          : ParserError: (CloseBraceToken:TokenId) [], ParseException
    + FullyQualifiedErrorId : MissingEndCurlyBrace

And when I Add a } at the end of line 40 i get this error

The Try statement is missing its Catch or Finally block.
At C:\home\dustin\IT\Pushover\emailmonitor.ps1:42 char:2
+ } <<<<
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : MissingCatchOrFinally

Thanks again for your time

Free Windows Admin Tool Kit Click here and download it now
November 21st, 2013 12:50am

This works just fine against Exchange 2013.  Maybe later I can test it against Exchange 2010

$MailboxName='userid@comeexchange.com'
$password='werhkjehrkewjbr'

Add-Type -Path 'C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll'

$sb={
    foreach($notEvent in $event.SourceEventArgs.Events){
        [String]$itmId = $notEvent.ItemId.UniqueId.ToString()
        $message = [Microsoft.Exchange.WebServices.Data.EmailMessage]::Bind($event.MessageData,$itmId)
        IF ($message.Subject -eq 'execprocess'){
            Start-Process -FilePath 'powershell' -ArgumentList '-File c:\scripts\opsalert.ps1'
        }
    }
}

$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)
$service.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials($MailboxName, $password)

Try{
    $service.AutodiscoverUrl($MailboxName,{$true})

    $fldArray = new-object Microsoft.Exchange.WebServices.Data.FolderId[] 1
    $Inboxid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)
    $fldArray[0] = $Inboxid
    $stmsubscription = $service.SubscribeToStreamingNotifications($fldArray, [Microsoft.Exchange.WebServices.Data.EventType]::NewMail)
    $stmConnection = new-object Microsoft.Exchange.WebServices.Data.StreamingSubscriptionConnection($service, 30) -ea Stop
    $stmConnection.AddSubscription($stmsubscription)
    
    Register-ObjectEvent -inputObject $stmConnection -eventName "OnNotificationEvent" -Action $sb -MessageData $service -ea Stop
    Register-ObjectEvent -inputObject $stmConnection -eventName "OnDisconnect" -Action {$event.MessageData.Open()} -MessageData $stmConnection -ea Stop
    $stmConnection.Open()
}
Catch{
    Throw $_
}  

November 21st, 2013 1:12am

I tried your script (with my information)

I received this error

Exception calling "AutodiscoverUrl" with "2" argument(s): "The Autodiscover service couldn't be located."
At C:\home\dustin\IT\Pushover\emailmonitor3.ps1:20 char:29
+     $service.AutodiscoverUrl <<<< ($MailboxName,{$true})
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

Free Windows Admin Tool Kit Click here and download it now
November 21st, 2013 1:28am

Are you sure Exchange webservices is running?  Is it behind a firewall and blocked?

November 21st, 2013 1:31am

I'm fairly certain its running, I installed it using the .msi, but not sure how to check if its running or not
Free Windows Admin Tool Kit Click here and download it now
November 21st, 2013 1:41am

I'm fairly certain its running, I installed it using the .msi, but not sure how to check if its running or not

What did you install and where?
November 21st, 2013 1:47am

What did you install and where?

Free Windows Admin Tool Kit Click here and download it now
November 21st, 2013 1:50am

That is only the client api.  It is not Exchange Web Services.  EWS is installed on the server.
November 21st, 2013 1:54am

Ok, so from the that link I used the command: 

Set-WebServicesVirtualDirectory -identity "CAS01\EWS (Default Web Site)" -externalurl https://mail.contoso.com/EWS/Exchange.asmx -BasicAuthentication:$True

But with my URL, and without the CAS01, it wouldn't work with that, and it gave no errors,

I then ran our Powershell script but still got the error with AutoDiscover


  • Edited by Dustin IT 21 hours 37 minutes ago
November 21st, 2013 9:23am

Ok, so from the that link I used the command: 

Set-WebServicesVirtualDirectory -identity "CAS01\EWS (Default Web Site)" -externalurl https://mail.contoso.com/EWS/Exchange.asmx -BasicAuthentication:$True

But with my URL, and without the CAS01, it wouldn't work with that, and it gave no errors,

I then ran our Powershell script but still got the error with AutoDiscover



Are you running this on a workstation or on the Exchange Server.
Free Windows Admin Tool Kit Click here and download it now
November 21st, 2013 10:49am

The Powershell script I am running from the Domain Controller, that has the Exchange Managed API installed. I ran the command you directed me to on the Exchange Server EMC
November 21st, 2013 10:51am

The script works. Something in your implementation is set up wrong or not set up. THe account you are using must be enabled for web access and a number of other things.  I would either contact you admin or vendor or try going through the docs until you are able to determine what is missing.

As I posted earlier, I will test on my 2010 setup later to see what may be not set up.  I will also attempt to use the non-autodiscover method although that is even less reliable unless you know exacly howyour domain is st up.

Start by going back over all of the Exchange install steps and see if you missed a piece.

Free Windows Admin Tool Kit Click here and download it now
November 21st, 2013 10:57am

Here is the M S Test tool.  It will let you test all modes of EWS on any version of EWS.

https://testconnectivity.microsoft.com/

November 21st, 2013 10:58am


  Test Steps
  Attempting to resolve the host name abc.org in DNS.
  The host name resolved successfully.
  Additional Details

  Testing TCP port 443 on host abc.org to ensure it's listening and open.
  The port was opened successfully.
  Additional Details
  Elapsed Time: 210 ms.

  Testing the SSL certificate to make sure it's valid.
  The SSL certificate failed one or more certificate validation checks.
  Additional Details
  Elapsed Time: 326 ms.

  Test Steps
  The Microsoft Connectivity Analyzer is attempting to obtain the SSL certificate from remote server abc.org on port 443.
  The Microsoft Connectivity Analyzer successfully obtained the remote SSL certificate.
  Additional Details
  Remote Certificate Subject: E=webmaster@gcstech.net, CN=web2.gcstech.net, OU=Web Services, O=GCS Tech, L=Spencer, S=Iowa, C=US, Issuer: E=webmaster@gcstech.net, CN=web2.gcstech.net, OU=Web Services, O=GCS Tech, L=Spencer, S=Iowa, C=US.
Elapsed Time: 306 ms.

  Validating the certificate name.
  Certificate name validation failed.
   Tell me more about this issue and how to resolve it

  Additional Details
  Host name abc.org doesn't match any name found on the server certificate E=webmaster@gcstech.net, CN=web2.gcstech.net, OU=Web Services, O=GCS Tech, L=Spencer, S=Iowa, C=US.
Elapsed Time: 0 ms.





  Attempting to test potential Autodiscover URL https://autodiscover.abc.org/AutoDiscover/AutoDiscover.xml
  Testing of this potential Autodiscover URL failed.
  Additional Details
  Elapsed Time: 174 ms.

  Test Steps
  Attempting to resolve the host name autodiscover.abc.org in DNS.
  The host name couldn't be resolved.
   Tell me more about this issue and how to resolve it

  Additional Details
  Host autodiscover.abc.org couldn't be resolved in DNS InfoDomainNonexistent.
Elapsed Time: 173 ms.



  Attempting to contact the Autodiscover service using the HTTP redirect method.
  The attempt to contact Autodiscover using the HTTP Redirect method failed.
  Additional Details
  Elapsed Time: 19 ms.

  Test Steps
  Attempting to resolve the host name autodiscover.abc.org in DNS.
  The host name couldn't be resolved.
   Tell me more about this issue and how to resolve it

  Additional Details
  Host autodiscover.abc.org couldn't be resolved in DNS InfoDomainNonexistent.
Elapsed Time: 19 ms.



  Attempting to contact the Autodiscover service using the DNS SRV redirect method.
  The Microsoft Connectivity Analyzer failed to contact the Autodiscover service using the DNS SRV redirect method.
  Additional Details
  Elapsed Time: 148 ms.

  Test Steps
  Attempting to locate SRV record _autodiscover._tcp.abc.org in DNS.
  The Autodiscover SRV record wasn't found in DNS.
   Tell me more about this issue and how to resolve it

  Additional Details
  Elapsed Time: 148 ms.






Free Windows Admin Tool Kit Click here and download it now
November 21st, 2013 11:13am

If your service isn't published or published correctly you may well get that result.

The mail domain must be public and it must be registered in DNS.  The firew2all must be open and the server certificate must be valid.  You have failed most of these tests.

If you intend on using this for public acess (users access from outside of company firewall) then you need to fix all of this.

I recommend hiring a consultant to help you design and implement your Exchange server.  Exchange is a beast.  It is not designed to be managed by basic Network Admins or by desktop support.

The next step is to test internal direct connectivity.  That is what I will do later today.  I will post back with a simple script to do tjis test.  I do not want to post the script without testing it and I don't really have time to set that up right now.

November 21st, 2013 11:35am

Thanks for your help, the network was setup before I started working here by an outside company (local) I came into without much documentation at all so I kind of have to uncover things as I go along. 

I do know that we can access our mail from home via https://abc.org/owa

So it is accessible from outside the local network. I'm not sure if the autodiscover is connected or not though

Free Windows Admin Tool Kit Click here and download it now
November 21st, 2013 12:20pm

Thanks for your help, the network was setup before I started working here by an outside company (local) I came into without much documentation at all so I kind of have to uncover things as I go along. 

I do know that we can access our mail from home via https://abc.org/owa

So it is accessible from outside the local network. I'm not sure if the autodiscover is connected or not though

My pint.  You are not trained in Exchange and are making all of the wrong assumptions.  I can point you but you will not guess your way through this.

Home connectivity has nothing to do with EWS.  It uses RPC over HTTP or IMAP or both or SMTP.  SMTP appears to be working correctly but with an invalid certificate.

It appears that you vendor did a raw setup with SMTP and opened the firewall - which is automatic during install.  Most of these vendors are not well trained in Exchange but can get it running. 

I will test later and post a simple internal test script that will tell you if EWS is installed correctly for local access.  If it isn't you will have to contact either the vendor or a consultant to help you fix it.

There is no substitute for training.  These systems ae very complex and use dozens of technologies.  Trianing gets you the view from 1000 feet and more training gets you closer.  It would take half a lifetime to guess through each bit.

Start with a good book on Exchange Administration for EX 2010.  Spend a week of dinners reaing it and do all of the exercises.  When you are done you will have an appreciation for what you are working with.  It is a very nice system but is not for the casual tech.

Are you running SBS?  If so that brings in many other interesting issues that you will have to deal with first.  You cannot easily run the EWS client on the Exchange server I it is on SBS.  The default security restrictions will not allow it.

You should not ever run a mail client other than a browser client on an Exchange server.  This can create many problems and can allow malware to be injected.

November 21st, 2013 12:41pm

It is Exchange 2007 running on Windows Sever 2003 sp2
Free Windows Admin Tool Kit Click here and download it now
November 21st, 2013 12:49pm

Then this line is wrong:

$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)

You are asking for a newer version than you have.

Is the WS2003 a DC?

November 21st, 2013 1:12pm

No the WS2003 isn't the DC, our DC is running Windows Server 2008
Free Windows Admin Tool Kit Click here and download it now
November 21st, 2013 2:35pm

No the WS2003 isn't the DC, our DC is running Windows Server 2008

Have you installed EWS on the Exchange server?

http://www.msexchange.org/articles-tutorials/exchange-server-2007/management-administration/configuring-exchange-server-2007-web-services-urls.html

Be sure you can pass all of these tests.

November 21st, 2013 2:51pm

Assuming your system is set up correctly this will get a connection  without the AutoDiscover feature.  It also only asks for EXC2007 SP1 support.

# uses Exchange 2007 SP1 compatibility.
$serviceURL=' https://  <fqdn>   /EWS/Exchange.asmx'
$scriptPathName='c:\scripts\opsalert.ps1' # requires fill path
$MailboxName='userid@comeexchange.com'
$password='werhkjehrkewjbr'

Add-Type -Path 'C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll'

$sb={
    foreach($notEvent in $event.SourceEventArgs.Events){
        [String]$itmId = $notEvent.ItemId.UniqueId.ToString()
        $message = [Microsoft.Exchange.WebServices.Data.EmailMessage]::Bind($event.MessageData,$itmId)
        if($message.Subject -eq 'execprocess'){
            Start-Process -FilePath 'powershell' -ArgumentList "-File $scriptPathName"
        }
    }
}

$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2007_SP1)
$service.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials($MailboxName, $password)
$service.Url=$serviceURL

Try{

    $fldArray = new-object Microsoft.Exchange.WebServices.Data.FolderId[] 1
    $Inboxid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)
    $fldArray[0] = $Inboxid
    $stmsubscription = $service.SubscribeToStreamingNotifications($fldArray, [Microsoft.Exchange.WebServices.Data.EventType]::NewMail)
    $stmConnection = new-object Microsoft.Exchange.WebServices.Data.StreamingSubscriptionConnection($service, 30) -ea Stop
    $stmConnection.AddSubscription($stmsubscription)
    
    Register-ObjectEvent -inputObject $stmConnection -eventName "OnNotificationEvent" -Action $sb -MessageData $service -ea Stop
    Register-ObjectEvent -inputObject $stmConnection -eventName "OnDisconnect" -Action {$event.MessageData.Open()} -MessageData $stmConnection -ea Stop
    $stmConnection.Open()
}
Catch{
    Throw $_
}  

If this doesn't work you will need to contact an Exchange consultant to go over your installation.  Since you are not Exchange trained I recommend doing this anyway if this is an important server.  Verifying that you actually have a good installation is critical to all future use of Exchange.  I have seen  to many vendors hack and install and leave the client floundering.  If your vendor is still available then you really should contact them to find the documentation and setup logs.  The logs should be in the root of the Exchange server and can be used to analyze what was installed.

In my experience taking over an unknown server is always tricky. I always allocate significant time to just validating what I have.  Once you get good at Exchange this is not too hard for a stand alone server.

Be happy you have 2007 and not 2003 or earlier.  They were very finicky.

Free Windows Admin Tool Kit Click here and download it now
November 21st, 2013 3:11pm

Thank you for that script I ran through the Test Email Autoconfiguration, and verified that AutoDiscover was installed and running

I tried the script above, and received a different error

Exception calling "SubscribeToStreamingNotifications" with "2" argument(s): "Method SubscribeToStreamingNotifications
s only valid for Exchange Server version Exchange2010_SP1 or later."
At C:\home\dustin\IT\Pushover\emailmonitor4.ps1:28 char:66
+     $stmsubscription = $service.SubscribeToStreamingNotifications <<<< ($fldArray, [Microsoft.Exchange.WebServices.D
ta.EventType]::NewMail)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

November 21st, 2013 3:21pm

Yup - not an error.  It is telling you exactly what it is telling you.

I didn't look at the 2007 capabilities.  We have noting older than 2010 excpt for on 2003 that is now being converted to Office365.  Al of my initial testing was against O365v in the cloud and EX2010.If I had known you were not using 2010 I would have told you to change that setting earlier.

This is why I recommend getting a trained person in to work with you.  Without a level of technical training that matches the product you will be wasting your time, the time of others and you are taking a chance on an unrecoverable failure.

If you are trained in AD and WS2003 or later you can get the training in a week at a local school.  I recommend you ask you boss to spring to have you trained or to hire a consultant.  It will save both time and money.

Free Windows Admin Tool Kit Click here and download it now
November 21st, 2013 3:31pm

Ok, well thanks for all your help, do you see any other way of automating this opsalert script when receiving email? Could I have outlook running all the time or something?
November 21st, 2013 3:43pm

Ok, well thanks for all your help, do you see any other way of automating this opsalert script when receiving email? Could I have outlook running all the time or something?

Outlook has rules.  Create a rule to do this and jut leave outlook running.  Post questions about how to use Outlook in the Outlook user forum.
Free Windows Admin Tool Kit Click here and download it now
November 21st, 2013 4:04pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics