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", SupportsShouldProcess=$true)]
    param(
        #The name of the task
        [Parameter(Mandatory=$true)]
        [Alias("Name")]
        $TaskName = "dir/taskname",
        # The name of the computer to connect to.
        # service command
        [Parameter(Mandatory=$true)]
        $Command = "",
        [string]$args = "",
            [Parameter(Mandatory=$false)][pscredential]
        [System.Management.Automation.Credential()]
        $credential = [pscredential]::Empty,
        #[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 
            
            $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
            
            
              
            $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
            }
       
            $a = @{}
            $cred = $credential
            if ($cred -ne $null -and $cred -ne [pscredential]::Empty) {
                $a["user"] = $username = $cred.UserName
                $a["password"] = $pass = $cred.GetNetworkCredential().Password
            } else {
                # throw "no credentials given!"
            }

            if (!$PSCmdlet.ShouldProcess( "creating task '$taskname' in path '$taskpath' for command '$command' with args '$args' ")) {
                $t = ScheduledTasks\New-ScheduledTask `
                    -Action $action `
                    -Trigger $triggers `
                    -Settings $settings `
                    -ErrorAction Stop -Verbose `
                    @a
                    #-TaskName $TaskName
            }
            $result = ScheduledTasks\Register-ScheduledTask `
                -TaskName $TaskName -RunLevel $runlevel -TaskPath $taskpath `
                -Action $action `
                -Trigger $triggers `
                -Settings $settings `
                -ErrorAction Stop -Verbose `
                @a

            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"
            if ($username -ne $null) {
                $task = $Task | Set-ScheduledTask -User $username -Password $pass 
            }

            return $task
            # 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


    }    
}