How to schedule a batch file to run on startup or shutdown

group-policyshutdownstartup-scriptsvbscriptwindows-server-2012-r2

I have 2 batch files that send emails intended to notify of a server shutdown or startup. The batch files call an exe with a single argument, the message to be sent. The exe comes from a vb.net program using system.net.mail.

The batch files work properly from a command prompt and emails are received.

Now I want these batch files to run automatically when the OS starts and when the OS is being shutdown, without any user having to log on.

I tried testing this on a Win 8.1 machine which I believe should work the same as on Server 2012 R2. If this is a bad assumption, please advise.

So here's what I tried:

1) Task Scheduler (but only for startup, there's no shutdown option)

2) Local Group Policy Editor > Computer Configuration > Windows Settings > Scripts (Startup/Shutdown)

In both cases the setup seemed pretty straightforward, but the emails are never sent.

Can someone give me ideas about considerations I clearly am not thinking about?

Is the problem permissions? How would I know that?

Is the problem "It looks scheduled but isn't"?

Is the problem that batch files can't be used in this way?

Since this is my first time doing this, I'm pretty certain I'm missing something basic.

Best Answer

This really isn't an answer due to the two limitations noted below but it's too long for a comment, so..

I did a simple test with the following two shortcomings:

  1. The scripts do not send email. I need the smtp relay of my ISP but it's too much hassle to find it.
  2. I'm testing on a Win10 preview, not a Win8.1. It's all I have this evening.

Inside of Local Group Policy Editor > Computer Configuration > Windows Settings > Scripts (Startup/Shutdown), I have put one startup powershell script in the startup directory and one shutdown powershell script in the shutdown directory.

I have taken special care to add the scripts under the Powershell Scripts tab inside each of the startup and shutdown policy nodes.

I have made sure I have a directory called c:\temp as I was too lazy to script it into existence.

I have also made sure powershell scripts are allowed by running:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

Here is the startup script:

if (!(Test-Path c:\temp\log.txt)) {New-Item -ItemType file -Path c:\temp\log.txt}
$timestamp = get-date 
$string = "$timestamp UP!"
$string | Out-File -FilePath c:\temp\log.txt -Append -NoClobber

Here is the shutdown script:

if (!(Test-Path c:\temp\log.txt)) {New-Item -ItemType file -Path c:\temp\log.txt}
$timestamp = get-date 
$string = "$timestamp DOWN!"
$string | Out-File -FilePath c:\temp\log.txt -Append -NoClobber

I then rebooted the computer. Here is the content of the c:\temp\log.txt file:

06/01/2015 00:07:45 DOWN!
06/01/2015 00:08:10 UP!

I would expect the same result with having it sending a mail, but one can't be sure of course until one actually tries..