powershellscheduled-taskspowershell-5.0

How to add another action when creating scheduled task in Powershell


There is a main.ps1 file that is uploaded to devices so it can create all the necessary tasks they need to run when distributed. Within this main.ps1 file I have added code to create a new task, but unlike the others it needs multiple actions and I am unsure of how to add more actions within the context of how the code is set up. The main.ps1 was originally created by a guy who has since left and I am just adding to it. Pertinent code below. Preferably 3 actions within the task.

$taskCommand = "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe"
$taskStartTime = [datetime]::Now.AddMinutes(1) 
$taskArguments="-WindowStyle Hidden -NonInteractive -Executionpolicy unrestricted"
 
$service = new-object -ComObject("Schedule.Service")
$service.Connect()
$rootFolder = $service.GetFolder("\")

$iscreate77Task=$true

Function set77Definition {
    param ($tDefinition,$tDesc, $tInterval, $tArgs)
            $tDefinition.RegistrationInfo.Description = "$tDesc"
            $tDefinition.Settings.Enabled = $true
            $tDefinition.Settings.AllowDemandStart = $true

            $tDefinition.Settings.DisallowStartIfOnBatteries=$false
            $tDefinition.Settings.RunOnlyIfNetworkAvailable=$true
            $tDefinition.Settings.ExecutionTimeLimit="PT1H"

            $tDefinition.Principal.RunLevel =1

            $triggers = $tDefinition.Triggers
            $trigger = $triggers.Create(2) 
            $trigger.StartBoundary = $taskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss")            
            #$trigger.Repetition.Interval= "PT"+"$tInterval"+"M"
            $trigger.Enabled = $false

            $action = $tDefinition.Actions.Create(0)
            $action.Path = "$taskCommand"
            $action.Arguments = "$tArgs"
}

 Function create77Task {
    param(
        $taskName = "Run_77",
        $taskScript = "C:\code-client\Run_77.ps1",
        $taskDescr = "Starts and stops process to facilitate launching 77",
        $taskArg = "$taskArguments -file $taskScript",
        $taskDefinition = $service.NewTask(0),
        $interval=2          
    )
       set77Definition -tDefinition $taskDefinition -tDesc $taskDescr -tInterval $interval -tArgs $taskArg
        $rootFolder.RegisterTaskDefinition("$taskName",$taskDefinition,6,"System",$null,5)
}

if($iscreate77Task){
create77Task
}

Solution

  • I would advise you modernise your code and use the scheduledtasks powershell library instead of the COM control

    New-ScheduledTask will accept an array of Actions. Take a look at the docs