Private/New-SpecScheduledTaskPrincipal.ps1

Function New-SpecScheduledTaskPrincipal {
    <#
    .SYNOPSIS
    This function creates a new scheduled task principal (user context) based on the provided parameters.
 
    .DESCRIPTION
    The New-SpecScheduledTaskPrincipal function creates a new scheduled task principal (user context) based on the specified parameters. It allows setting the user account under which the task will run and whether to run with the highest privileges.
 
    .PARAMETER RunAs
    Specifies the user account or security group to run the task as.
 
    .PARAMETER RunWithHighestPrivilege
    Indicates whether the task should be run with the highest privileges. If this switch is used, the task will run with the highest available privileges; otherwise, it will run with limited privileges.
 
    .EXAMPLE
    $taskPrincipal = New-SpecScheduledTaskPrincipal -RunAs "DOMAIN\User"
    Creates a new scheduled task principal with the specified user account "DOMAIN\User" and default privileges.
 
    .EXAMPLE
    $taskPrincipal = New-SpecScheduledTaskPrincipal -RunAs "LocalService" -RunWithHighestPrivilege
    Creates a new scheduled task principal with the "LocalService" account and runs the task with the highest available privileges.
 
    .NOTES
    Author: owen.heaume
    Date: August 10, 2023
    Version: 1.0
    Status Codes:
    - Successful assignment: Returns the created task principal object.
    - Unable to set the task principal: Returns 912.
    #>


    [cmdletbinding()]
    param (
        [parameter (Mandatory = $true)]
        [string]$RunAs,

        [switch]$RunWithHighestPrivilege
    )

    try {
        # Set the task run level
        $taskPrincipal = New-ScheduledTaskPrincipal -GroupId $RunAs -ea Stop -ev x

        # Run with highest privileges if selected
        if ($RunWithHighestPrivilege.IsPresent) {
            write-verbose "Run level set to 'Highest'"
            $taskPrincipal.RunLevel = "Highest"
        } else {
            write-verbose "Run level set to 'Limited'"
            $taskPrincipal.RunLevel = "Limited"
        }

        return $taskPrincipal

    } catch {
        write-error "Unable to set the task principal: $x"
        return 912
    }
}