2 min read

Powershell - Create Scheduled task

Powershell - Create Scheduled task

So i was to create a new scheduled task using Powershell for clienthealth script, and went a bit "overboard" with it, resulting in this script which can be re-used for other things aswell.
I used a task for "ClientHealth" as an example in this one.

Haven't made a parameter for "Task Settings" yet, so you have to add those in the script. Been having some troubles putting those into a parameter

<#
    Script to create scheduled task

    Creation date:
    2022-04-29
#>

# If needed remove previous task
[CmdletBinding()]
param (
    [Parameter(HelpMessage="Enter the name of the task")]
    [string]
    $TaskName = "ConfigMgr Client Health",

    [Parameter(HelpMessage="If you want a previous task with the same name deleted / Overwritten before creation")]
    [bool]
    $OverwritePreviousTask = $true,

    [Parameter(HelpMessage="Description")]
    [string]
    $Description = "Task will run ClientHealth script to eg. fix ConfigMgr Client if needed.",

    [Parameter(HelpMessage="At which RightsLevel should the task be run? Valid choices 'Limited' or 'Highest'")]
    [string]
    $RunLevel = "Highest",

    [Parameter(HelpMessage="What to be executed.")]
    [string]
    $Execution = "Powershell.exe",

    # Example "$(New-ScheduledTaskTrigger -AtLogon)"
    [Parameter(HelpMessage="What should trigger the task.")]
    [array]
    $Trigger = (
        $(New-ScheduledTaskTrigger -Daily -DaysInterval 1 -At 12pm),
        $(New-ScheduledTaskTrigger -AtLogon)
    ),

    [Parameter(HelpMessage="Exectuion arguments")]
    [string]
    $ScheduledTaskArguments = '-ExecutionPolicy Bypass -NonInteractive -file "\\SERVERUNC\PUB\ClientHealth\ConfigMgrClientHealth.ps1" -Config "\\SERVERUNC\pub\ClientHealth\Config.xml"',

    # SID "S-1-5-18" = "NT AUTHORITY\SYSTEM"  
    [Parameter(HelpMessage="Set under which account to execute the task")]
    [string]
    $User = "S-1-5-18"
)

if($OverwritePreviousTask -eq $true){
    Write-Output "Checking for previous '$TaskName' and deleting if it does..."
    try{
        $PreviousTask = Get-ScheduledTask -TaskName $TaskName
    }
    catch{
        $Message = $_
        Write-Warning $Message
    }
    if(!([string]::IsNullOrEmpty($PreviousTask))){
        try{
            Write-Output "Previous task found, deleting..."
            Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false -ErrorAction SilentlyContinue -Verbose
        }
        Catch{
            $Message = $_
            Write-Warning "Error deleting task... $Message, script will exit"
            Exit 1
        }
    }
}

# Set Task creation parameters    
    # Create Task Action
    $Action = New-ScheduledTaskAction -Execute $Execution -Argument $ScheduledTaskArguments

    # settings / Conditions for task to be applied after creation
    $Settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -Hidden -ExecutionTimeLimit (New-TimeSpan -Minutes 10) -Compatibility Win8

# Create new Scheduled Task
try{
    Write-Output "Trying to create scheduled task '$TaskName'"
    Register-ScheduledTask -TaskName $TaskName -Action $Action -Trigger $Trigger -User $User -RunLevel $RunLevel -Description $Description
    Write-Output "$TaskName Created..."
}
Catch{
    $Message = $_
    Write-Warning "Could not create task '$TaskName'... $Message"
}

# Set task settings
try {
    Write-Output "Trying to set specified task settings on '$TaskName'"
    Set-ScheduledTask -TaskName $TaskName -Settings $Settings 
}
catch {
    $Message = $_
    Write-Warning "Error when trying to configure task according to settings.. $Message"
}