How can I run a PowerShell script every time a computer starts?
Task Scheduler is probably the best way to run a PowerShell script since it includes a scheduling option for startup execution. Create your PowerShell script (for this example, I'll use C:\Scripts\Startup.ps1), and then schedule powershell.exe --File C:\Scripts\Startup.ps1 (changing the filename to whatever you used). If the computer doesn't have an execution policy that will allow your script to run, add --ExecutionPolicy RemoteSigned or another appropriate policy. Add --NoLogo to suppress the normal copyright banner that PowerShell displays.
You can then create the scheduled task. You can do this using a PowerShell command on Windows Server 2012 and Windows 8; you can use the Task Scheduler GUI on any version of Windows. On Windows Server 2012 and Windows 8, I actually prefer to use the PSScheduledJob functionality, which retains the results of the script for review in PowerShell. That way I can have my scripts output logging information (via Write-Output) and review it whenever I need to. For example:
Register-ScheduledJob –Name AtStartup –FilePath C:\Scripts\Startup.ps1
-Credential (Get-Credential DOMAIN\Username)
-ScheduledJobOption (New-ScheduledJobOption –DoNotAllowDemandStart)
-Trigger (New-JobTrigger –AtStartup)
That command will create the scheduled job, run the PowerShell script under the DOMAIN\Username credential (you'll be prompted for the password when the job is created) and keep 30 sets of results on disk. I can then use Get-Job and Receive-Job in PowerShell to retrieve those results, identifying the job by the AtStartup job name that I assigned. I also configured the job to not allow on-demand starting, meaning someone can't go in and run it manually.
About the author
Don Jones is a well-known and respected PowerShell expert and educator. He's co-author of three books on PowerShell (see PowerShellBooks.com for a list). You can find his content online, including his PowerShell Q&A forums, by visiting DonJones.com.
Dig Deeper on Windows administration tools
Related Q&A from Don Jones
If you don't need a GUI display, PowerShell can be hosted in several hosting applications so you can use cmdlets instead of a graphical input prompt. Continue Reading
Each PowerShell version has different features made useful by add-ins and snap-ins, so admins have to pay attention to what features work where. Continue Reading
Wondering how to get PowerShell to read XML files? Our expert explains a few methods you could use. Continue Reading
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.