How to Schedule a PowerShell Script in Windows


To totally unlock this section you need to Log-in


Login
PowerShell is quickly taking over as the defacto scripting language in Windows environments--in fact, Microsoft has decreed to all of it's software units that they must create PowerShell cmdlet's with full functionality to the software in all future releases.

That means we have to learn how to run scripts from the Task Scheduler.

Quick Procedure

Write down and save your script to a local drive on the server as a PS1 (*.ps1) file.

Next, load Task Scheduler from Start > All Programs > Accessories > System Tools. The version we are going to use here ships with Windows Server 2008 R2, but the concepts should be the same on earlier (and future) releases.

How to Schedule a PowerShell Script in Windows

How to Schedule a PowerShell Script in Windows

To create a new scheduled task, click Create Task from the right-hand “Actions” panel. At a minimum, you should fill out the following information:

General Tab

Name of the task – for example, Intranet Backup.

A description is also useful, but not mandatory.

Ensure the user's account running the task has the necessary permissions to run the job: if the job will run over the network you'll need extra permissions (to logon on remote systems, for example, or to logon directly in database servers) to be able to access all you'll need to let the job to complete successfully.

Select Run whether the user is logged in or not and, if the job will run only locally on the system on which reside the job, tick the Do not store password checkbox.

For certain operations, you may also need to enable the Run with highest privileges option. As this should only be enabled when necessary, I would recommend testing the script from Task Scheduler with the option disabled and only enable if the script does not work without it.

How to Schedule a PowerShell Script in Windows

How to Schedule a PowerShell Script in Windows

Triggers Tab

Click New and add your schedule, as required. In the example below I am going for daily at 2:00AM

How to Schedule a PowerShell Script in Windows

How to Schedule a PowerShell Script in Windows

Make sure that you setup a schedule on the triggers pane, but because nothing is really new there we will skip over to the Actions pane where the magic happens. When you add a new action to be called in the program / script section you need to specify the location of the main powershell.exe file which, by default, resides at C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe.

Actions Tab

Click New. Ensure the action is set to Start a program and type Powershell.exe in the “Program/Script” box. In the “Add arguments (optional)” box, type, for example, &'C:\scripts\script.ps1' replacing the path and name with the details for your script.

Wrapping the file path and name in single quotation marks allows you to specify spaces in the text.

How to Schedule a PowerShell Script in Windows

How to Schedule a PowerShell Script in Windows

When you click OK to confirm task creation, you will be prompted to enter the password for the account you selected to run the script. Enter the password and click OK.

You should now see your script in the Task Scheduler Library (if not, click Refresh in the right-hand panel). To test the script, highlight it in the console and click Run from the right-hand panel.

How to Schedule a PowerShell Script in Windows

How to Schedule a PowerShell Script in Windows

Check that the changes required are performed (for this example it was checking to ensure the backup file was being created in the folder when the task ran) and leave it to run on the schedule. Don’t forget to perform regular checks in the future to test the script continues to run as expected.

Get your script ready

Surprising as it might sound, your script might actually not be ready to run in a scheduled task as is. This happens if it uses cmdlets from a particular PowerShell module or snap-in, and it worked for you interactively because you used a specialized shell (e.g. Exchange Management Shell) or a tool like PowerGUI Script Editor which loads the modules for you.

[tweet]

If you indeed are using using any non-default cmdlets, simply add Add-PSSnapin or Import-Module to the beginning of the script. For example:

Add-PSSnapin Quest.ActiveRoles.ADManagement

Schedule the task

To schedule a task simply start Windows Task Scheduler and schedule powershell.exe executable passing the script execution command as a parameter. The -File parameter is the default one so simply specifying the script path as the argument would work in a lot of cases:

How to Schedule a PowerShell Script in Windows

How to Schedule a PowerShell Script in Windows

You can find powershell.exe in your system32\WindowsPowerShell\v1.0 folder.

Report task success or failure

If you want your script to report success or failure (or some sort of other numerical result) simply use the exit keyword in the script to pass the value, for example:

exit 4

Then your Windows Task Scheduler will show the value in the Last Run Result (you might need to hit F5 to refresh the column in the task scheduler):

Passing parameters

If you need to pass parameters things get a little trickier. Say, you have a script which adds two numbers:

param($a=2, $b=2)

"Advanced calculations ahead"
exit $a + $b

To pass the numbers as parameters, you would want to use powershell.exe -Command instead of powershell.exe -File. This -Command argument will then have the script invocation operator &, path to the script, and the parameters.

For example:

Program: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Add argument (optional): -Command "& c:\scripts\hello.ps1 -a 2 -b 3"

If you want to also get your exit code from the script, you would need to re-transmit that by adding exit $LASTEXITCODE to the command.

For example:

Program: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Add argument (optional): -Command "& c:\scripts\hello.ps1 -a 2 -b 3; exit $LASTEXITCODE"

Run x86 PowerShell on x64 Windows

On 64-bit versions of Windows you actually have both 64-bit and 32-bit versions of PowerShell.

In most cases you don’t care but in some cases (e.g. specific COM objects being used) you might need specifically a 32-bit version.

To get that to run, simply pick the proper executable when you schedule the task:

Regular PowerShell (64-bit version on 64-bit Windows):

%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe

32-bit PowerShell (x86):

%SystemRoot%\syswow64\WindowsPowerShell\v1.0\powershell.exe

Other options

To learn about all parameters PowerShell executable has simply run it with /? option (from either cmd.exe or a PowerShell session).

You can normally use -noprofile to make sure that nothing in the PowerShell profile interferes with the task.

[tweet]

Also, if your Execution Policy does not allow running scripts the -ExecutionPolicy parameter comes handy allowing you to make an exception just for this task. For example:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -File c:\scripts\hello.ps1 -ExecutionPolicy RemoteSigned

Here are some other parameters provided by PowerShell:

-PSConsoleFile

Loads the specified Windows PowerShell console file. To create a console
file, use Export-Console in Windows PowerShell.

I guess you could use that is you want the exact environment you have in the predefined shell from Exchange, AD, or SQL. For example:

PowerShell -PSConsoleFile SqlSnapIn.Psc1

-Version

Starts the specified version of Windows PowerShell.

-NoLogo
Hides the copyright banner at startup.
This is not really relevant for scheduled tasks.

-NoExit
Does not exit after running startup commands.
Might be useful for troubleshooting.

-Sta
Start the shell using a single-threaded apartment.
If your script needs STA mode.

-NonInteractive
Does not present an interactive prompt to the user.
Not really relevant for scheduled tasks.

-InputFormat
Describes the format of data sent to Windows PowerShell. Valid values are "Text" (text strings) or "XML" (serialized CLIXML format).

-OutputFormat
Determines how output from Windows PowerShell is formatted. Valid values are "Text" (text strings) or "XML" (serialized CLIXML format).

-WindowStyle
Sets the window style to Normal, Minimized, Maximized or Hidden.

-EncodedCommand
Accepts a base-64-encoded string version of a command. Use this parameter to submit commands to Windows PowerShell that require complex quotation marks or curly braces.
# To use the -EncodedCommand parameter:

$command = 'dir "c:\program files" '
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
powershell.exe -encodedCommand $encodedCommand
Can be useful when having to pass advanced expressions and getting issues with parser.

1 thought on “How to Schedule a PowerShell Script in Windows”

Comments are closed.