-1.6 C
New York
Tuesday, January 16, 2024

Proceed Your Automation To Run As soon as After Restarting a Headless Home windows System


There are occasions once you can’t keep away from having to reboot a system and proceed with an automation process.

Once you hit certainly one of these, you begin down the street of discovering the built-in ways in which Home windows means that you can stage a process to start out when the system restarts.

There is only one small catch – most of them require a consumer logon to be able to course of. On the numerous headless servers that make up the cloud – this merely isn’t an possibility.

Discovering out methods to fulfill this requirement could be a little arduous to unravel at first as a result of a few of these places are within the machine registry – which may give the primary blush impression that they course of and not using a consumer logon.

Run and RunOnce Registry Keys

There are 4 registry location the place you’ll be able to configure one thing to run on reboot, two of which solely run one time:

HKEY_LOCAL_MACHINESoftwareMicrosoftWindowsCurrentVersionRun HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionRun HKEY_LOCAL_MACHINESoftwareMicrosoftWindowsCurrentVersionRunOnce HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionRunOnce

Yow will discover out methods to configure these places by looking the web, nonetheless, in case your state of affairs requires automation to restart with out the necessity for a consumer logon, then you’re out of luck with all of them. The The HKEY_LOCAL_MACHINE places nonetheless require a consumer to logon – however they merely course of for EVERY consumer who logs on.

Lively Setup Registry Keys

Lively Setup keys are one other Home windows mechanism that permits a command to be staged. To make this work you populate they key HKEY_LOCAL_MACHINESofwtareMicrosoftActive SetupInstalled Elements with a correctly formatted command. When a consumer logs on, in the event that they haven’t run that key, the command is run after which the secret’s copied to HKEY_CURRENT_USERSofwtareMicrosoftActive SetupInstalled Elements as a performed marker.

As soon as once more, a consumer should logon for these keys to be run.

Distinctive Necessities

Listed below are the distinctive necessities, as I do know them, that may trigger you to be looking for an answer to this drawback:

  1. It’s worthwhile to run or proceed an automation course of after a Home windows machine reboots.

  2. You want this to occur whether or not or not a consumer ever logs on (frequent for servers).

  3. You want the method to run with full native administrator rights (together with no UAC prompts).

  4. You want it to run WITHOUT offering a consumer password to the duty for a number of of those causes:

    • you don’t wish to code passwords into automation code (particularly not ones with administrator privileges)

    • you don’t or can’t know an admin password for an present consumer id

    • you don’t wish to create a consumer id with admin rights and delete it afterward simply to perform this process

Answer: Self-Deleting Scheduled Process That Runs As The System Account (Runs Solely As soon as)

By the point you resort to the duty scheduler, you’re nonetheless in for some adventures discovering what instructions provides you with the gold. Particularly if you’re utilizing PowerShell.

It is because:

  • PowerShell scheduled jobs require a username and password and will not be out there on older variations.

  • PowerShell process scheduling CMDLets are able to doing this, however are solely out there on Server 2012 R2 / Home windows 8.1 and later and are extra advanced to exercise.

  • Lots of the pattern configurations you’ll discover on the Web robotically embody each a username and password because the particular person writing them assumed that will be the one method to achieve entry to admin rights on a headless reboot.

So the magic sauce is to make use of schtasks.exe to schedule a run as soon as process that deletes itself.

Warning About schtasks /Z

schtasks.exe has a “/Z” change that’s purported to self-delete a process. On newer OSes you may have additionally add /V1 to keep away from a crimson herring error that you’ve got malformed XML. Nevertheless, in my testing with these switches the duty would by no means self-delete – it stored working on each startup. (solely examined on Server 2012 R2)

The under code is written in PowerShell however makes use of schtasks.exe – which is definitely extra straight ahead than the ScheduledTask CMDLets.

Up to date Code

The under code’s main house is on the next repository (the place it could be improved upon in comparison with the under): https://gitlab.com/missionimpossiblecode/MissionImpossibleCode

Instance 1: Write Out A Script To Schedule

This technique works properly when the code to run after a restart is pretty temporary and it isn’t sensible to schedule the pre-restart code to run itself once more.

Code to Write A Script To Be Referred to as On Restart (Together with self-deletion of the duty)

The primary little bit of code writes out a scheduled process script.


$scriptlocation = "$env:windirtempafterreboot.ps1"
"Write-EventLog -Message 'HeadlessRestartTask: hello I ran on reboot' -LogName System -Supply EventLog -EventId 333"| out-file $scriptlocation
start-sleep -s 2" | out-file $scriptlocation -append
"schtasks.exe /delete /f /tn HeadlessRestartTask" | out-file $scriptlocation -append

Code to Schedule The Above Script

#This code schedules the above script
schtasks.exe /create /f /tn HeadlessRestartTask /ru SYSTEM /sc ONSTART /tr "powershell.exe -file $scriptlocation"
Write-Host "`"$scriptlocation`" is scheduled to run as soon as after reboot."

Instance 2: Script Scheduling Itself for Put up-Restart Resuming

If a script must schedule itself to run as soon as on a headless restart then the script itself should reside on the native disk.

A simple method to deal with the necessity to restart the script at a sure checkpoint is to have an optionally available change built-in to the script that forwards execution to the restart place within the code. (That is “-SkipToPhaseTwo” within the under instance.)

Within the under code the particular $MyInvocation object is used to search out the complete path to the at the moment executing script so that you don’t must customise it on every use.

If (!$SkipToPhaseTwo)
{
  
  
  schtasks.exe /create /tn "HeadlessRestartTask" /ru SYSTEM /sc ONSTART /tr "powershell.exe -file $($MyInvocation.MyCommand.Definition) -SkipToPhaseTwo"
  Write-Host "`"$scriptlocation`" is scheduled to run as soon as after reboot."
  Restart-Laptop -Power
}
Write-Output "The system has restarted, persevering with..."

"schtasks.exe /delete /f /tn HeadlessRestartTask"


Instance 3: Oneliner Self-Deleting With No Script File

I give this instance with trepidation as a result of in case your code is just not tremendous easy, it shortly turns into citation parsing hell. You’ll discover I’ve gone to lengths to keep away from an additional quotes even only for this straightforward instance.

schtasks.exe /create /f /tn HeadlessRestartTask /ru SYSTEM /sc ONSTART /tr "powershell.exe -executionpolicy remotesigned -command 'Write-EventLog -Message HeadlessRestartTask_hi_I_ran_on_reboot -LogName System -Supply EventLog -EventId 333 ; schtasks.exe /delete /f /tn HeadlessRestartTask'"

Instance 4: PowerShell Code for Comparability to Schtasks.exe


$TaskTrigger = (New-ScheduledTaskTrigger -atstartup)
$TaskAction = New-ScheduledTaskAction -Execute Powershell.exe -argument "-ExecutionPolicy Bypass -File $scriptlocation"
$TaskUserID = New-ScheduledTaskPrincipal -UserId System -RunLevel Highest -LogonType ServiceAccount
Register-ScheduledTask -Power -TaskName HeadlessRestartTask -Motion $TaskAction -Principal $TaskUserID -Set off $TaskTrigger

This Approach In Manufacturing

I’m a co-maintainer of the Chocolatey bundle for putting in PowerShell. The approach mentioned, in addition to very related code, are within the present PowerShell Chocolatey bundle – it’s used to repair up the PowerShell PSModulePath when PowerShell / WMF 5.1 is put in immediately over PowerShell WMF 3.0.

On this state of affairs the damaging alterations to the PSModulePath are performed someday throughout the restart by the post-boot end up processing of the WMF 5.1 Home windows Replace – so the repair should run after Home windows Updates completes processing throughout the restart.

Right here is the code



Supply hyperlink

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles