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

    Question

  • 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
    Monday, November 18, 2013 10:47 PM

Answers

  • 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.


    ¯\_(ツ)_/¯

    • Marked as answer by Dustin IT Monday, November 25, 2013 5:03 PM
    Thursday, November 21, 2013 8:27 PM

All replies

  • 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.


    ¯\_(ツ)_/¯

    Tuesday, November 19, 2013 3:35 AM
  • Well if you could help me on the installing event code into Exchange and then assigning it that would be great as well!

    Thanks

    Wednesday, November 20, 2013 5:34 PM
  • 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.


    ¯\_(ツ)_/¯

    Wednesday, November 20, 2013 5:42 PM
  • 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!

    Wednesday, November 20, 2013 5:49 PM
  • 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.


    ¯\_(ツ)_/¯

    Wednesday, November 20, 2013 6:09 PM
  • 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
    Wednesday, November 20, 2013 6:12 PM
  • 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.


    ¯\_(ツ)_/¯

    Wednesday, November 20, 2013 6:12 PM
  • 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

    Wednesday, November 20, 2013 6:18 PM
  • 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.


    ¯\_(ツ)_/¯


    • Edited by jrv Wednesday, November 20, 2013 7:09 PM
    Wednesday, November 20, 2013 6:21 PM
  • 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


    ¯\_(ツ)_/¯

    Wednesday, November 20, 2013 6:26 PM

  • 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!

    Wednesday, November 20, 2013 6:35 PM
  • 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.
    
       ....


    ¯\_(ツ)_/¯



    • Edited by jrv Wednesday, November 20, 2013 7:14 PM
    Wednesday, November 20, 2013 7:13 PM
  • 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

    Wednesday, November 20, 2013 8:14 PM
  • I am running it now.  Works good but I need to create a proper script to call.  Right now it just events.


    ¯\_(ツ)_/¯

    Wednesday, November 20, 2013 8:27 PM
  • I am running it now.  Works good but I need to create a proper script to call.  Right now it just events.


    ¯\_(ツ)_/¯

    So your saying the script above works for you? Could I see what you're using? Where in the script is it calling my script? (Opsalert.ps1)

    Thanks!

    Wednesday, November 20, 2013 8:42 PM
  • You cannot directly call a powershell script.  It has to be run like this:

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


    ¯\_(ツ)_/¯


    • Edited by jrv Wednesday, November 20, 2013 9:47 PM
    Wednesday, November 20, 2013 9:47 PM
  • 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

    Wednesday, November 20, 2013 9:50 PM
  • 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 $_
    }  
    


    ¯\_(ツ)_/¯


    • Edited by jrv Wednesday, November 20, 2013 10:13 PM
    Wednesday, November 20, 2013 10:12 PM
  • 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

    Wednesday, November 20, 2013 10:28 PM
  • Are you sure Exchange webservices is running?  Is it behind a firewall and blocked?


    ¯\_(ツ)_/¯

    Wednesday, November 20, 2013 10:31 PM
  • I'm fairly certain its running, I installed it using the .msi, but not sure how to check if its running or not
    Wednesday, November 20, 2013 10:41 PM
  • 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?

    ¯\_(ツ)_/¯

    Wednesday, November 20, 2013 10:47 PM
  • What did you install and where?


    ¯\_(ツ)_/¯

    I installed Exchange Web Services 2.0 and the files are located here C:\Program Files\Microsoft\Exchange\Web Services\2.0
    Wednesday, November 20, 2013 10:50 PM
  • That is only the client api.  It is not Exchange Web Services.  EWS is installed on the server.

    ¯\_(ツ)_/¯

    Wednesday, November 20, 2013 10:54 PM
  • 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 Thursday, November 21, 2013 2:19 PM
    Thursday, November 21, 2013 2:19 PM
  • 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.

    ¯\_(ツ)_/¯

    Thursday, November 21, 2013 3:45 PM
  • 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
    Thursday, November 21, 2013 3:46 PM
  • 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.


    ¯\_(ツ)_/¯

    Thursday, November 21, 2013 3:52 PM
  • 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/


    ¯\_(ツ)_/¯

    Thursday, November 21, 2013 3:54 PM

  •   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.






    Thursday, November 21, 2013 4:09 PM
  • 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.


    ¯\_(ツ)_/¯

    Thursday, November 21, 2013 4:31 PM
  • 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

    Thursday, November 21, 2013 5:15 PM
  • 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.


    ¯\_(ツ)_/¯

    Thursday, November 21, 2013 5:37 PM
  • It is Exchange 2007 running on Windows Sever 2003 sp2
    Thursday, November 21, 2013 5:45 PM
  • 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?


    ¯\_(ツ)_/¯

    Thursday, November 21, 2013 6:07 PM
  • No the WS2003 isn't the DC, our DC is running Windows Server 2008
    Thursday, November 21, 2013 7:30 PM
  • 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.


    ¯\_(ツ)_/¯

    Thursday, November 21, 2013 7:47 PM
  • 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.


    ¯\_(ツ)_/¯


    • Edited by jrv Thursday, November 21, 2013 8:07 PM
    Thursday, November 21, 2013 8:07 PM
  • 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

    Thursday, November 21, 2013 8:17 PM
  • 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.


    ¯\_(ツ)_/¯

    • Marked as answer by Dustin IT Monday, November 25, 2013 5:03 PM
    Thursday, November 21, 2013 8:27 PM
  • 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?
    Thursday, November 21, 2013 8:39 PM
  • 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.

    ¯\_(ツ)_/¯

    Thursday, November 21, 2013 9:00 PM
  • Note also that Outlook on Exchange 2003 has server side rules.  Each user can create rules to manage incoming mail.  There is a Wizard that helps design rules.

    ¯\_(ツ)_/¯

    Monday, November 25, 2013 5:15 PM