none
Script runs, but doesn't produce unless user logged in RRS feed

  • Question

  • Here's a weird one, and I'm not sure which forum is proper for this. But since it deals with a powershell script, I gotta start somewhere.

    I've a powershell script called sendmail.ps1 which I have configured to create and send an email to me when run. Works flawlessly. So I've set it up in task manager to run the script whenever a Windows backup fails. Works great, provided the administrator is actually logged on to the server. I've set it up in task manager to run with the Administrator login, highest privileges, and hidden. Again, works great when the administrator is actually logged on to the server. (Server 2012R2). However, if the administrator is not logged on it appears that no email is sent. The task still shows "completed successfully" in task manager, yet no email is received - therefore I  assume it's not sent. I can find no errors in the event viewer (is there a specific container in event viewer I need to check for this?) What do I need to do so the sendmail.ps1 script will actually send an email when the administrator is not logged on to the server?

    Here's some things I've tried in various combinations.

     - Task is configured/optimized for Server 2012R2 under the general tab.

     - Have tried it both hidden and not hidden

     - Hive tried it with the administrator account and the system account. Both work only when administrator is logged on.

    Saturday, December 6, 2014 8:25 PM

Answers

  • Well this is weird - but it works now. I tried like you said and set it for Vista/2008 compatibility and it still didn't work. However, leaving that compatibility setting, under the settings tab for "if the task is already running the following rule applies" I set it to queue another instance. Knowing that the event code for a successful backup is 4 and that multiple event codes are generated for a failed backup, I surmise that multiple instances of the task were being started and clashing. So after making this change, it's worked without being logged on 3 times in a row. Yeah, I get 2 emails, but that's fine. Why instances would clash when not logged on, but it seemed to work when I was logged on is perplexing. But at this point, if continued testing of this setup works, I really don't care how many e-mails the script sends.

    Sunday, December 7, 2014 6:40 PM

All replies

  • Hard to tell unless you post your script here. Anyway, you must capture the console output of your script like so, then examine it:

    Send.ps1  1>>c:\Logs\send.log  2>>&1

    Make sure the folder c:\Logs exists and is open to all accounts.

    Saturday, December 6, 2014 9:03 PM
  • Thanks. below is the script, which works just fine.

    $EmailTo = myemail@myisp.com
    $EmailFrom = "thatemail@myisp.com"
    $Subject = "Server Backup Failed!!!"
    $Body = "Last night's local server backup failed. This is not an emergency, but you need to call Carl at 669-8170"
    $SMTPServer = "smtp.mail.yahoo.com"
    $SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
    $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
    $SMTPClient.EnableSsl = $true
    $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("thatemail@myisp.com", "password");
    $SMTPClient.Send($SMTPMessage)

    When I run from the command prompt with:

    powershell -file "C:\Client Apps\Powershell Scripts\sendmail.ps1"

    it works flawlessly. However, in an attempt to create a log file I use your switches and run:

    powershell -file C:\Client APps\Powershell Scripts\sendmail.ps1" 1>>c:\log.txt 2>>&1

    it won't run, identifying the 1>> as an invalid argument. So there's no log file. So obviously, adding this to the task in task manager is kinda moot at this point. I suspect that maybe there's a typo in the switch you provided?

    Saturday, December 6, 2014 9:49 PM
  • powershell -file C:\Client APps\Powershell Scripts\sendmail.ps1" 1>>c:\log.txt 2>>&1


    The command generates the expected output on my machine but without the -file switch. Could it be the missing double quote in your command?

    Saturday, December 6, 2014 10:21 PM
  • Well this is weird. After trying it with your switches and it not working, I put the action in Task Manager back to what I originally had. Then I set a backup time for 5:10pm, unplugged the backup drive so it would fail, then logged off the computer. Much to my surprise, I got the "backup failed" email as expected, showing an email creation/send time of 5:10pm.

    Right now, I've change the backup time to 5:30pm then rebooted the server. At the moment, I'm waiting for that time to come and go, and I'll see what happens.

    Saturday, December 6, 2014 10:27 PM
  • >> is a cmd.exe feature.

    If you intend to redirect the output of powershell.exe itself, you will need to put the command line in a cmd.exe shell script (.cmd or .bat file) and schedule that.


    -- Bill Stewart [Bill_Stewart]

    Saturday, December 6, 2014 10:41 PM
    Moderator
  • Okay, here we go. First I created a batch file called backupfailed.bat with a single line it it that reads:

    powershell -file "C:\Client Apps\Powershell Scripts\sendmail.ps1"

    Next, I altered the task action to run a program:

    "c:\Client Apps\Powershell Scripts\backupfailed.bat" 1>>c:\log\log.txt 2>>&1

    Then I scheduled the backup to run at 7:15pm with the backup hard drive disconnected so backup would fail on purpose, triggering the backupfailed.bat file. Then I manually executed the task by right-clicking it and selecting run. Worked perfectly and I got the "backup failed" email just as I should.

    Then rebooted the server and waited 15 minutes after the reboot for the backup attempt to fail and trigger the task. The task in task manager says "successful 0x0". However, with the user not logged on to the server no email was received and I did get the below log.txt file.

    C:\Windows\system32>powershell -file "C:\Client Apps\Powershell Scripts\sendmail.ps1"
    Exception calling "Send" with "1" argument(s): "Failure sending mail."
    At C:\Client Apps\Powershell Scripts\sendmail.ps1:11 char:1
    + $SMTPClient.Send($SMTPMessage)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : SmtpException

    C:\Windows\system32>powershell -file "C:\Client Apps\Powershell Scripts\sendmail.ps1"

    Note that if I am logged onto the server with the Administrator Login, the log file is 0 bytes in size with nothing in it. However, if the Administrator is not logged onto the server, I get the above in the log file. I've already confirmed that the administrator's group is a member of the backup operator's group, so that should take care of the "log on as a batch job" requirement.

    Sunday, December 7, 2014 12:38 AM
  • If you cannot post your script then this is just BS.

    Why are you not using Send-MailMessage.

    How can you expect anyone to help you if you keep everything a secret.  You are a technicians worst nightmare as a user.  Please try to address these deficiencies.

    Thank you.


    ¯\_(ツ)_/¯

    Sunday, December 7, 2014 12:58 AM
  • Check the ego at the login page and look up. Every time a noob such as myself posts in these MS forums, there's always someone who has to take the attitude of "I'm a better person than you because I know what you don't know". Never fails. But as long as this thread is now, I can understand how you could miss it. The script is posted in this thread, over three hours ago a few posts up from this one.

     >> why are you not using Send-MailMessage.

    I don't know. I'm not a powershell guru. The sendmail script I'm using is one I got out of the scripting forum a few weeks ago while searching that forum blindly looking for something that would work. The script I'm using seemed to work. It was just today I discovered things didn't work if the administrator is not logged on. Perhaps instead of making yourself feel superior by insulting the lack of knowledge by others such as myself, you could actually "be" superior, read entire threads before replying to them, and only respond in such a thread if you actually want to help. The addition of one's emotions into the process is counter-productive for everyone.

    Sunday, December 7, 2014 1:42 AM
  • So you admit that you have been told this before.  Your bitching is still not a script.

    Drop the lame duck routine, "Oh I am a noobie and I don't know anything.  Please can someone rescue me from my virgin state?"

    Post your script.  Is  that so hard?


    ¯\_(ツ)_/¯

    Sunday, December 7, 2014 2:26 AM
  • Several points:

    1. "Failure sending mail" is the error. The PowerShell script you are running is generating the error message. If you didn't write the script, you will need to ask the script's author for possible remedies. Otherwise, you can learn a bit more PowerShell and try using send-mailmessage, as suggested.

    2. If the script works from a prompt, then you have a task scheduler problem/question, not a scripting problem/question.

    3. You can trigger sending email based on events in the event log without even needing a script.


    -- Bill Stewart [Bill_Stewart]

    Sunday, December 7, 2014 3:11 AM
    Moderator
  • Hi Bill,

     Apparently, in Server 2012R2 the task scheduler has the "send an email" option depreciated, and it doesn't function. Otherwise, I agree with you and wouldn't be worrying about a script. I did use that option in Server 2003, but it quit working for me when SSL/TLS became a requirement for sending mail. I can't be sure, but it looks like that even if the task scheduler's send email action was not depreciated, it would probably still not work because it doesn't allow me to set port, SSL or smtp login credentials. So I'd still need a script. Or am I missing something here that should probably be obvious if I knew where to look?

    I did a quick check of the Send-MailMessage option, and I see no parameters for setting the SMTP server to port 587. I also can't yet figure out how to get the mailbox login id and password in the -credentials parameter. I think I may have just missed it on my initial perusal of that command, as I did see the -UseSSL option parameter. Overall, for my purpose, the send e-mail option within task manager doesn't work since it's depreciated, and it 'appears' to this novice that when it comes to sendmail or Send-MailMessage, neither has an advantage over the other. Though I am still researching the Send-MailMessage, since it's script construction seems different from what I presently have working in my sendmail.ps1 script.

    I found the sendmail.ps1 script in one of these forums several weeks ago, and I thought it was working out great until I tested it without the administrator being logged in. I don't think it's a script issue myself, but more of a task scheduler issue. However, I get script errors as shown in the log file above if it runs when the administrator is not logged on to the server. So that's why I'm a bit unsure on where to go. Kinda expect that if this thread had appeared in the task scheduler support forum, they would have blamed the script and sent me here. It's like six of one, or half dozen of the other.

    I'm not expecting you to respond to this, since there's nothing useful in this particular post, and that's fine. I'll just keep chugging with the forum search function as well as google until I get something that works. I'll happen eventually. Thanks.

    Sunday, December 7, 2014 3:54 AM
  • If you want to capture the script's output for diagnostics, add Start-Transcript to the top of the script.

    Second, don't discount the possibility that there isn't anything wrong with the script.

    Is the firewall enabled, and are they any Deny events that correspond to that delivery failure?

    If it's failing during the smtp conversation, then you can use Message Analyzer to capture and decode that:

    https://www.microsoft.com/en-us/download/details.aspx?id=44226


    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

    Sunday, December 7, 2014 4:16 AM
    Moderator
  • Thanks for the feedback mjolinor. I've not downloaded the analyzer, because from reading the description for it, it appears I'd have to be logged on for it to be useful. Remember, the task words flawlessly if logged on, but not if logged off. So far, the only thing I can get is output to a log file of:

    Exception calling "Send" with "1" argument(s): "Failure sending mail."
    At C:\Client Apps\Powershell Scripts\sendmail.ps1:11 char:1
    + $SMTPClient.Send($SMTPMessage)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : SmtpException

    From looking at it, the "error" is being generated by the very parameter that creates the log file - though the log file is successfully created. Weird.

    With the "Start-Transcript" added, where does it capture the output to if the task runs while not logged on to the server computer? Or do I just add the path\filename as a parameter after Start-Transcript ?

    This is truly perplexing to me, as it doesn't make any sense that it runs perfectly when the administrator is logged onto the server. But when not logged on and the task runs that executes the pwershell script, the task itself will show as executed successfully, and I can't find any errors in the basic logs of the event viewer. Perhaps it's one of the other containers in event viewer where something is logged, but there's so many of them, I've not a clue which one. Right now, I'm working through each one at a time to see if anything jumps out at me.

    If you're interested, here's some additional background to explain why it has to run with the administrator logged off. This server runs a 3rd party practice management software program for a dental office. The program is poorly constructed, as it has "memory leaks". This server has 32Gb of memory, and because of the memory leaks, it will run out of useable available memory about every 36-48 hours. So for this reason I've got a task set up to just reboot the server daily at 6am, one hour prior to employees arriving for business. This ensures they start the day "fresh" and the server won't lock up on them during business hours. The business owner absolutely loves this program, and even after I explained the issue to him as best I could in a way I hope he could understand, he's not changing software vendors. I've already notified the developer of this problem, and apparently they've been aware of the memory leak for years, and their solution is "reboot daily". All I can say about that is, they're lucky they don't work for me.

    So it's very likely that with daily reboots, this server could go for weeks without anyone logging on to it. Therefore, the powershell script needs to run weather the user is logged on or not. Else, backups could not occur for weeks and no one would ever know it - until it's to late of course.

    Sunday, December 7, 2014 4:42 AM
  • Okay

    First of all, before you ask questions about a cmdlet you're not familiar with, you should at least read the Help for that cmdlet.  Most of the time that will get your question answered much faster.

    Get-Help Start-Transcript -Full

    Second, you have to be logged in to run Message Analyzer, but you don't have to be logged in as the same account the scheduled task is using.  You'll need to test it, but I suspect that the scheduled task only runs successfully if you're logged on with the same account the task is using.

    Set up the scheduled task, then log on as a different user and run Message Anaylzer while the task is scheduled to run.  You'll be looking for an outbound smtp connection (port 25) to that yahoo mail server.



    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

    Sunday, December 7, 2014 5:42 AM
    Moderator
  • Thanks for your patience. Guess when I typed help start-transcript and got nothing related to the start-transcript cmdlet, it would have helped had read what it did put there. the 'get-help" did the trick of course. :)

    After setting this up, I set the backup to run a stayed logged on until it ran, failed, and triggered my "failed backup notify" task. That task executed perfectly as expected, and below is the transcript log, which shows no problems. Right now, I've set it up to run the backup a bit later, and have rebooted the server. I'm now waiting for the backup task to run and fail so it will trigger the failed backup task. I'll post the log file from that run in the next post.

    **********************
    Windows PowerShell transcript start
    Start time: 20141207005927
    Username: TAVARY\Administrator
    RunAs User: TAVARY\Administrator
    Machine: BATSERVER (Microsoft Windows NT 6.3.9600.0)
    Host Application: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.EXE -file C:\Client Apps\Powershell Scripts\sendmail.ps1
    Process ID: 7100
    **********************
    Transcript started, output file is c:\log\output.txt

    PS>$global:?
    True
    **********************
    Windows PowerShell transcript end
    End time: 20141207005930
    **********************

    Sunday, December 7, 2014 6:18 AM
  • Okay here's the log file from when the task ran after reboot, and before I logged on. I should also clarify that I've already set-executepermission unrestricted for powershell, and I've confirmed that the administrator's login is a member of the administrators group, and that the administrators group is a member of the backup operators group. I know that's necessary to run scripts with a user account that's not actually logged on.

    I can see in the below that an error is definitely generated, but I don't know how to interpret what the log file is telling me; which 'argument' is the problem?

    **********************
    Windows PowerShell transcript start
    Start time: 20141207011532
    Username: TAVARY\Administrator
    RunAs User: TAVARY\Administrator
    Machine: BATSERVER (Microsoft Windows NT 6.3.9600.0)
    Host Application: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.EXE -file C:\Client Apps\Powershell Scripts\sendmail.ps1
    Process ID: 6512
    **********************
    Transcript started, output file is c:\log\output.txt
    Exception calling "Send" with "1" argument(s): "Failure sending mail."
    At C:\Client Apps\Powershell Scripts\sendmail.ps1:11 char:1
    + $SMTPClient.Send($SMTPMessage)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : SmtpException

    PS>$global:?
    True
    **********************
    Windows PowerShell transcript end
    End time: 20141207011546
    **********************

    approaching 2am here, and I'm calling it a night. Back on it in the morning, as a fresh rested mind may be just what is needed for a eureka moment to figure this out.

    Sunday, December 7, 2014 6:25 AM
  • PowerShell has a port option and has for many years.

    Here is the help: https://www.google.com/?gws_rd=ssl#newwindow=1&q=send%3Dmailmessage

    This is from the help:

    -Port<Int32>

    Specifies an alternate port on the SMTP server. The default value is 25, which is the default SMTP port. This parameter is available in Windows PowerShell 3.0 and newer releases.


    ¯\_(ツ)_/¯


    • Edited by jrv Sunday, December 7, 2014 12:02 PM
    Sunday, December 7, 2014 9:15 AM
  • I have been able to reproduce your problem.  It seems to happen only after you first create the task.

    Using your code on Windows 8.1 or WS2012R2 the task fails when set to run as a WS2012R2 or Windows 8.1 task.  Toggling to Vista/2008 compatiblilty and running the task appears to fix it.  I can even set the task back to 8.1/2012 compatibility and it continues to work.

    I suspect your issue may be related. If so then this is a true bug and should br reported to MS Connect.


    ¯\_(ツ)_/¯


    • Edited by jrv Sunday, December 7, 2014 12:06 PM
    Sunday, December 7, 2014 12:05 PM
  • Well this is weird - but it works now. I tried like you said and set it for Vista/2008 compatibility and it still didn't work. However, leaving that compatibility setting, under the settings tab for "if the task is already running the following rule applies" I set it to queue another instance. Knowing that the event code for a successful backup is 4 and that multiple event codes are generated for a failed backup, I surmise that multiple instances of the task were being started and clashing. So after making this change, it's worked without being logged on 3 times in a row. Yeah, I get 2 emails, but that's fine. Why instances would clash when not logged on, but it seemed to work when I was logged on is perplexing. But at this point, if continued testing of this setup works, I really don't care how many e-mails the script sends.

    Sunday, December 7, 2014 6:40 PM
  • This would seem to be a task scheduler question rather than a scripting question.

    -- Bill Stewart [Bill_Stewart]

    Sunday, December 7, 2014 9:28 PM
    Moderator