Windows 2012 startup script
Hi All,
I'm spinning up some Amazon VMs running Windows 2012 R2. I want to have a script to run whenever the server boots/reboots. Note that I don't want it to run at logon, but actually when the server starts.
I've been googling and it seems like you can do it in powershell like this:
$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:30
Register-ScheduledJob -Trigger $trigger -FilePath C:\myscript.bat -Name script
This doesn't work though.
Ideally this needs to be in powershell. I don't have access to the GUI (or at least I can't rely on it), so things like setting up group policy in the GUI won't work.
Can anyone help? I'm not really a Windows person.
Ta....
b0redom
Re: Windows 2012 startup script
have you tried setting something under:
HKLM\Software\Microsoft\Windows\CurrentVersion\Run
Re: Windows 2012 startup script
Task scheduler allows run at startup, just slap the credentials in the box when you click apply and point it to the batch file. I do seem to remember having an issue running a batch file resolved by a free program to convert batch to EXE files so it could be run as admin so the 2 may work together?
Re: Windows 2012 startup script
Ok, so I've cracked it, and the answer for posterity is:
Run this in your AWS user data or whatever is creating your servers:
Quote:
$taskName = "MyStartupTask"
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-File "C:\<myPowerShellScript.ps1>"'
$principal = New-ScheduledTaskPrincipal -UserId SYSTEM -LogonType ServiceAccount -RunLevel Highest
$trigger = New-ScheduledTaskTrigger -AtStartup -RandomDelay 00:00:30
$definition = New-ScheduledTask -Action $action -Principal $principal -Trigger $trigger -Description "Run $($taskName) at startup"
Register-ScheduledTask -TaskName $taskName -InputObject $definition
This will add a new task to run on server startup which calls C:\<myPowerShellScript.ps1>
It seems that task manager only really likes running powershell, or at least I had issues making it execute other bits and bobs, so I in my myPowerShellScript.ps1 I put:
Quote:
& c:\somebatchfile.bat
....and it magically springs to life.
I'm pretty sure no one else here will ever need this, but it drives me nuts when I find someone on the Internet has the same problem and either leaves it as an unsolved problem or adds, "I fixed it." with no details....