Answer

Use Task Scheduler to run a PowerShell script during every startup

How can I run a PowerShell script every time a computer starts?

    Requires Free Membership to View

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

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

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: