Q

Use Task Scheduler to run a PowerShell script during every startup

With some simple configuration, admins can run a PowerShell script each time a computer starts with the help of the Task Scheduler GUI and cmdlets.

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)
     -MaxResultCount 30
     -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.

This was first published in August 2013

Dig deeper on Windows PowerShell Scripting

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

1 comment

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

SearchServerVirtualization

SearchCloudComputing

SearchExchange

SearchSQLServer

SearchWinIT

SearchEnterpriseDesktop

SearchVirtualDesktop

Close