Private/Create-SpecScheduledTask.ps1

function Create-SpecScheduledTask {
    <#
    .SYNOPSIS
    This function creates a new scheduled task with provided parameters.
 
    .DESCRIPTION
    The Create-SpecScheduledTask function creates a new scheduled task based on the specified parameters, including the task name, description, path, action, trigger, principal, and settings.
 
    .PARAMETER TaskName
    Specifies the name of the scheduled task.
 
    .PARAMETER Description
    Specifies the description of the scheduled task.
 
    .PARAMETER TaskPath
    Specifies the path for the task to be created.
 
    .PARAMETER Action
    Specifies the task action to be performed.
 
    .PARAMETER Trigger
    Specifies the trigger settings for the task.
 
    .PARAMETER Principal
    Specifies the user context under which the task will run.
 
    .PARAMETER Settings
    Specifies the settings for the task.
 
    .EXAMPLE
    $taskAction = New-SpecScheduledTaskAction -IsPs1Script $true -Path "C:\Scripts\MyScript.ps1"
    $taskTrigger = New-SpecScheduledTaskTrigger -Trigger "Daily" -Time "02:00"
    $taskPrincipal = New-SpecScheduledTaskPrincipal -RunAs "DOMAIN\User"
    $taskSettings = New-SpecScheduledTaskSettingsSet
 
    $taskStatus = Create-SpecScheduledTask -TaskName "MyTask" -Description "My Task" -TaskPath "\MyTasks" -Action $taskAction -Trigger $taskTrigger -Principal $taskPrincipal -Settings $taskSettings
    Creates a new scheduled task named "MyTask" with specified action, trigger, principal, and settings.
 
    .NOTES
    Author: owen.heaume
    Date: August 10, 2023
    Version: 1.0
    Status Codes:
        914- An error occurred creating the task using Register-ScheduledTask
    #>

    [cmdletbinding()]
    param (
        [string]$TaskName,
        [string]$Description,
        [string]$TaskPath,
        [object]$Action,
        [object]$Trigger,
        [object]$Principal,
        [object]$Settings
    )

    $params = @{
        TaskName    = $TaskName
        Description = $Description
        TaskPath    = $TaskPath
        Action      = $Action
        Trigger     = $Trigger
        Principal   = $Principal
        Settings    = $Settings
    }

    try {
        write-verbose "Creating Scheduled Task"
        Register-ScheduledTask @params -ErrorAction Stop -ErrorVariable x
        write-verbose "Scheduled Task created successfully"
    } catch {
        Write-Warning "Register-ScheduledTask: An error occurred creating the task: $x"
        return 914
    }
}