How would I go about getting a Powershell script on a set of computers to run periodically throughout the day while the computer is on? (we already use the "at startup" or "at logon" but some of the computers are left on without logins for days. We also can't use a regular Scheduled Task because these scripts report data to a server, and we don't want 300 computers hitting the server all at the same second. We also would like to avoid having the script be left running, with the delays determined by the script, because it sometimes crashes.)
Is there a way to either:
I guess one way to do this as a Scheduled Task would be to have a random delay of 0-5 min at the beginning of the script, but then we'd like to avoid that delay when testing or when invoked at startup or login.
2 Answers
Is there a way to run a script when the GPO is applied?
Yes. You can create a scheduled task that will trigger when a specific event occurs:
On an event
This trigger causes the task to run when specific event entries are added to an event log. You can choose between specifying basic event trigger settings or custom event trigger settings. If you choose the basic event trigger settings, a single event from a specific event log will trigger the task. You choose the event log that contains the event, the event publisher name, and specify the event identifier.
Source Triggers
The eventID you need for the trigger is probably 8006:
The Group Policy service reserves event IDs between 8000 and 8007 to indicate a particular type of Group Policy processing completed successfully.
Source Troubleshooting Group Policy Using Event Logs
1It appears that the Group Policy Management Editor, in Computer Configuration/Preferences/Control Panel Settings/Scheduled Tasks, it allows you to create an "Immediate Task", specifically created for running things after a GPO refresh.
Configure an Immediate Task Item (At least Windows 7)
For computers that are running Windows Server® 2012 or Windows® 8, Immediate Task (At least Windows 7) preference items, ( Immediate Task (Windows Vista and later) preference items if running Windows Server® 2008 R2 or Windows® 7), allow you to create tasks to be run immediately and then removed each time Group Policy refreshes. Immediate Task preference items do not provide a selection of actions or triggers because they always create a task and then delete it after it has run.
The only gotcha was that I had to specify a valid user for it to run as ("NT AUTHORITY\SYSTEM" in this case), and it worked exactly like I wanted.