Use PowerShell to Create Scheduled Task in New Folder


Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to create a new scheduled task in a specific folder.

Microsoft Scripting Guy, Ed Wilson, is here. Today I want to combine several of the scripts I have discussed this week based on scheduled tasks. Specifically, I am going to do the following:

  1. Check to see if a specific scheduled task exists. If it does, delete it.
  2. Check to see if a specific folder for scheduled tasks exists. If it does, do not create it.
  3. Create and register a new scheduled task in that specific folder.
  4. Modify the settings on that newly created scheduled task.

To do this, I am going to combine the various pieces of script I have used this week. To make the script a bit easier to read, I am putting the script into functions. These are not advanced functions, and they do not have good function names. The value of today’s exercise is to show how to combine various pieces of script to perform a specific task. More complex tasks are actually the norm for IT pros, so knowing how to put stuff together to accomplish a more complex process is valuable. Let's dive in…

Group script together in functions

The first thing I do is take my basic script from Use PowerShell to Create Scheduled Tasks Folders, and turn it into a simple function. My function accepts a single parameter, and that is the new folder name (or folder path). Because the CreateFolder method generates an error if a folder exists, I decide to add a bit of script to check to see if the folder exists before I attempt to create it. However, the GetFolder method generates an error if the folder does not exist. Hmm…

I decided to use a simple Try/Catch/Finally routine to do my folder check. To ensure that I enter the Try/Catch routine, I change the ErrorActionPreference to “Stop” instead of “Continue”, which is the default. I then set this value back in my Finally block. Here is the complete function:

Function New-ScheduledTaskFolder

    {

     Param ($taskpath)

     $ErrorActionPreference = "stop"

     $scheduleObject = New-Object -ComObject schedule.service

     $scheduleObject.connect()

     $rootFolder = $scheduleObject.GetFolder("\")

        Try {$null = $scheduleObject.GetFolder($taskpath)}

        Catch { $null = $rootFolder.CreateFolder($taskpath) }

        Finally { $ErrorActionPreference = "continue" } }

Now I need to create the function that will create and register my new scheduled task. I used the script from Use PowerShell to Create Scheduled Tasks. The only thing I did to modify it was to put it in a function and create two input parameters: TaskName and TaskPath. Here is the function:

Function Create-AndRegisterApplogTask

{

 Param ($taskname, $taskpath)

 $action = New-ScheduledTaskAction -Execute 'Powershell.exe' `

  -Argument '-NoProfile -WindowStyle Hidden -command "& {get-eventlog -logname Application -After ((get-date).AddDays(-1)) | Export-Csv -Path c:\fso\applog.csv -Force -NoTypeInformation}"'

 $trigger =  New-ScheduledTaskTrigger -Daily -At 9am

 Register-ScheduledTask -Action $action -Trigger $trigger -TaskName `

  $taskname -Description "Daily dump of Applog" -TaskPath $taskpath

}

To completely automate creating a scheduled task, often we modify the scheduled task settings after it is created. To do this, I use the script from Use PowerShell to Configure Scheduled Tasks. Once again, all I did was plop the script in a function and create two input parameters. These are the same parameters I used in the previous function: TaskName and TaskPath. Here is the function:

Function Create-NewApplotTaskSettings

{

 Param ($taskname, $taskpath)

 $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `

    -Hidden -ExecutionTimeLimit (New-TimeSpan -Minutes 5) -RestartCount 3

 Set-ScheduledTask -TaskName $taskname -Settings $settings -TaskPath $taskpath

}

After I have created my three functions, I create an entry point to the script. It is here that I define my two input parameters, and I check to see if the scheduled task previously exists. This is because I first created the scheduled task in the root folder, but now I want to create it in my new scheduled task folder (I do not know of a way to move a scheduled task from one folder to another, so it was easier to delete and re-create it.) Here is the command I use to do that:

If(Get-ScheduledTask -TaskName $taskname -EA 0)

  {Unregister-ScheduledTask -TaskName $taskname -Confirm:$false}

Now I simply call the function to create the new scheduled task folder, call the function to create the new scheduled task, and call the function to configure the task. Here is that script:

New-ScheduledTaskFolder -taskname $taskname -taskpath $taskpath

Create-AndRegisterApplogTask -taskname $taskname -taskpath $taskpath | Out-Null

Create-NewApplotTaskSettings -taskname $taskname -taskpath $taskpath | Out-Null

The complete script is shown here:

Function New-ScheduledTaskFolder

    {

     Param ($taskpath)

     $ErrorActionPreference = "stop"

     $scheduleObject = New-Object -ComObject schedule.service

     $scheduleObject.connect()

     $rootFolder = $scheduleObject.GetFolder("\")

        Try {$null = $scheduleObject.GetFolder($taskpath)}

        Catch { $null = $rootFolder.CreateFolder($taskpath) }

        Finally { $ErrorActionPreference = "continue" } }

    

Function Create-AndRegisterApplogTask

{

 Param ($taskname, $taskpath)

 $action = New-ScheduledTaskAction -Execute 'Powershell.exe' `

  -Argument '-NoProfile -WindowStyle Hidden -command "& {get-eventlog -logname Application -After ((get-date).AddDays(-1)) | Export-Csv -Path c:\fso\applog.csv -Force -NoTypeInformation}"'

 $trigger =  New-ScheduledTaskTrigger -Daily -At 9am

 Register-ScheduledTask -Action $action -Trigger $trigger -TaskName `

  $taskname -Description "Daily dump of Applog" -TaskPath $taskpath

}

 

Function Create-NewApplotTaskSettings

{

 Param ($taskname, $taskpath)

 $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `

    -Hidden -ExecutionTimeLimit (New-TimeSpan -Minutes 5) -RestartCount 3

 Set-ScheduledTask -TaskName $taskname -Settings $settings -TaskPath $taskpath

}

### ENTRY POINT ###

$taskname = "applog"

$taskpath = "PoshTasks"

If(Get-ScheduledTask -TaskName $taskname -EA 0)

  {Unregister-ScheduledTask -TaskName $taskname -Confirm:$false}

New-ScheduledTaskFolder -taskname $taskname -taskpath $taskpath

Create-AndRegisterApplogTask -taskname $taskname -taskpath $taskpath | Out-Null

Create-NewApplotTaskSettings -taskname $taskname -taskpath $taskpath | Out-Null

Here is what the script looks like in my Windows PowerShell ISE:

Image of command output

Because I am planning to use this script for automation purposes, there is no output. So when I run the script, I do not see anything. I instead open the Scheduled Task tool to ensure that it is there and ready. As you can see here, it worked perfectly.

Image of menu

Now you have some good ideas for using Windows PowerShell for scheduled tasks. Scheduled Task Week will continue tomorrow when I will talk about more cool stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

Comments (4)

  1. Andre says:

    The script is not wokring! Seems to be missing quotes and double quotes everywhere!

  2. Niall says:

    Check lines ending with `. This means the statement continues on the next line and there should be no line break.

  3. Niall says:

    Very nice script. I like it. Please can you check when you call New-ScheduledTaskFolder you do so with taskname param?

  4. Tamm says:

    Hi, this is so good. I need just one more stuff. Can you create new task with highest privileges, to run like Admin?

Skip to main content