functions/new-task.ps1
function new-task { <# .Synopsis creates a task on specified computer .Description A Detailed Description of what the command does .Example New-SvcTask #> [CmdletBinding(DefaultParameterSetName="startatboot")] param( #The name of the task [Parameter(Mandatory=$true)] $TaskName = "dir/taskname", # The name of the computer to connect to. # service command [Parameter(Mandatory=$true)] $Command = "", [string]$args = "", $UserName = $null, $pass = $null, $credentials = $null, #[Parameter(ParameterSetName = "startatboot", Mandatory=$true)] [switch][bool] $startAtBoot = $false, [Timespan] $repetitionInterval = [Timespan]::Zero, #[Parameter(ParameterSetName = "startat", Mandatory=$true)] [DateTime] $startAt = [Datetime]::MinValue, [switch][bool] $force = $true, $runLevel = "Highest", $workingdir = $null ) process { # Import the module Import-Module scheduledtasks $user = $UserName $taskpath = (Split-Path $TaskName -Parent) if ([string]::IsNullOrEmpty($taskpath)) { $taskpath = "\" } else { $taskpath = "\$taskpath\" } <# if ($taskpath -ne "\") { $scheduleObject = New-Object -ComObject schedule.service $scheduleObject.connect() $rootFolder = $scheduleObject.GetFolder("\") $rootFolder.CreateFolder("$taskpath") $scheduleObject.Dispose() } #> $taskname = split-path $TaskName -Leaf $a = @{} if ([System.IO.Path]::IsPathRooted($command)) { if (!(test-path $command)) { write-warning "task command '$command' not found" } } else { if ((test-path $command)) { $abs = (get-item $command).fullname write-warning "converting relative path '$command' to absolute: '$abs'" $command = $abs } elseif ((get-command $Command -ErrorAction Ignore) -eq $null) { write-warning "task command '$command' not found. maybe you meant to pass a full path?" } } if (![string]::IsNullOrEmpty($args)) { $a += @{ argument = $args } } if ($workingdir -eq $null) { $workingdir = split-path -Parent $command } write-host "creating task '$taskname' in path '$taskpath' for command '$command' with args '$args' " $action = ScheduledTasks\new-scheduledtaskaction -execute $command @a -ErrorAction Stop -Verbose -WorkingDirectory $workingdir $triggers = @() if ($repetitionInterval -ne [Timespan]::Zero -and !$startAtBoot.IsPresent) { # if repetition interval is set, assume user wanted to start the task as soon as possible $startAtBoot = $false if ($startat -eq [datetime]::MinValue) { $startat = [datetime]::Now.AddMinutes(2) } } if ($startAtBoot) { $trig = ScheduledTasks\New-ScheduledTaskTrigger -AtStartup -ErrorAction Stop -Verbose $triggers += @($trig) } elseif ($startAt -ne [datetime]::MinValue) { #if ($startAt -lt (get-date)) { # $startat = $startAt.AddDays(1) #} $trig = ScheduledTasks\New-ScheduledTaskTrigger -Daily -DaysInterval 1 -At $startAt $triggers += @($trig) } else { throw "no triggers defined. please use $startat or $startatboot" } $settings = ScheduledTasks\New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -DontStopOnIdleEnd $cred = $credentials if ($cred -eq $null) { if ([string]::IsNullOrEmpty($pass)) { $cred = Get-Credential -UserName $user -Message "Please provide credentials for service user" } else { $securepass = $pass | ConvertTo-SecureString -AsPlainText -Force $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $user,$securepass } } $username = $cred.UserName $pass = $cred.GetNetworkCredential().Password if ($cred -eq $null) { throw "no credentials given!" } $existing = ScheduledTasks\Get-ScheduledTask -TaskName $TaskName -ErrorAction Ignore -TaskPath $taskpath if ($existing -ne $null -and $force) { $null = ScheduledTasks\Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false -Verbose -TaskPath $taskpath } $result = ScheduledTasks\Register-ScheduledTask -TaskName $TaskName -User $username -Password $pass -Action $action -Trigger $triggers -RunLevel $runlevel -ErrorAction Stop -Verbose -TaskPath $taskpath -Settings $settings if ($result -eq $null) { throw "could not register task $TaskName" } $task = ScheduledTasks\Get-ScheduledTask -TaskName $TaskName -TaskPath $taskpath if ($repetitionInterval -ne $null -and $repetitionInterval -ne [timespan]::Zero) { # manually set repetition (it cannot be set when creating startatboot and daily triggers $Task.Triggers[0].Repetition.Interval = "PT$($repetitionInterval.totalminutes)M" $Task.Triggers[0].Repetition.StopAtDurationEnd = $false } if ($startAt -ne [datetime]::MinValue) { # manually set repetition to 1 day - the task starts once a day and repeats for a duration of 1 day #$Task.Triggers[0].Repetition.StopAtDurationEnd = $true $task.Triggers[0].Repetition.Duration = "P1D" $Task.Triggers[0].StartBoundary = $startAt.tostring("yyyy-MM-ddTHH:mm:ss") } #make sure that "stop the task if it runs longer than" is disabled $Task.Settings.ExecutionTimeLimit = "PT0S" $task = $Task | Set-ScheduledTask -User $username -Password $pass # Create a new task #$task = New-Task #$task.Settings.Hidden = $false #$timespan = [System.TimeSpan]::MaxValue #$timespan = New-TimeSpan -Days 9999 #$task.Settings.ExecutionTimeLimit = [System.Xml.XmlConvert]::ToString($timespan) # Add an action and a trigger #$task.Principal = new-sc #$User = "legimi\jakub.pawlowski" #$trig = New-JobTrigger -AtStartup #$file = 'task.xml' #Remove-Item $file #$task.XmlText > $file # Register the task #$task.Principal.RunLevel = 1 #$task.Principal.LogonType = 1 #$task.Principal.UserId = $user # if ($additionalConfig -ne $null) { #assume that triggers are added in additionalconfig script # $t = $additionalConfig.Invoke($task); # if ($t -ne $null) { # no idea why this is returned as a collection # $task = $t[0] # } #} #else { # $task = Add-TaskTrigger -Task $task -OnBoot #} #$task.Principal = $cred #$taskToStart = Get-ScheduledTask -Name $TaskName #Remove-Task -Name $taskName #$result = Register-ScheduledTask -Name $TaskName -Task $task -ComputerName $ComputerName -RunCredential $cred #if ($result -eq $null) { # throw "could not register task $TaskName" #} #& schtasks /Delete /tn $taskName #& schtasks /Create /tn $taskName /Xml $file #$folder = split-path -Parent $TaskName #$leaf = split-path -Leaf $TaskName #$taskToStart = Get-ScheduledTask -Name $leaf -folder $folder -ComputerName $ComputerName #if ($result -eq $null) { # throw "task $TaskName not found on computer $ComputerName" #} return $task #Start-Task -Task $taskToStart #Stop-Task -Task $taskToStart } } |