Windows Scheduled Task - Create

Octopus.Script exported 2022-03-29 by harrisonmeister belongs to ‘Windows’ category.

Create Windows scheduled task. If the task exists it will be torn down and re-added to ensure consistency

Parameters

When steps based on the template are included in a project’s deployment process, the parameters below can be set.

Name

TaskName

The name of the Scheduled Task

User

RunAsUser = System

The User that the task will run as

Password

RunAsPassword

Specifying a password allows the task to run when the user is not logged on to the server.

Action

Command

The Action that the task executes. Usually a path to the executable

Arguments

Arguments

A value that specifies any arguments to be passed to run the task.

Schedule

Schedule = DAILY

When the Task is triggered

Start Time

StartTime = 12:00

The Time the task will run. Use the format HH:mm

Start Date

StartDate

The date the task will start running. use the format MM/dd/yyyy

Modifier

Modifier

A value that specifies how often the task runs within its schedule type. For ONCE, ONSTART, ONLOGON and ONIDLE any value can be used since it will be ignored (They do not use modifiers with MO).

Interval

Interval

A value that specifies the repetition interval in minutes.

Duration

Duration

A value that specifies the duration to run the task. The time format is HH (24-hour time).

RunWithElevatedPermissions

RunWithElevatedPermissions

null

Days

Days

A value that specifies the day of the week to run the task. Valid values are: MON, TUE, WED, THU, FRI, SAT, SUN and for MONTHLY schedules 1 - 31 (days of the month). The wildcard character (*) specifies all days.

StartNewTaskNow

StartNewTaskNow = False

null

TaskStatus

TaskStatus = ENABLE

Whether the task is enabled, disabled, or left as-is when this step completes

Script body

Steps based on this template will execute the following PowerShell script.

$ErrorActionPreference = "Stop";
Set-StrictMode -Version "Latest";

# use http://msdn.microsoft.com/en-us/library/windows/desktop/bb736357(v=vs.85).aspx for API reference

Function Create-ScheduledTask($TaskName,$RunAsUser,$RunAsPassword,$TaskRun,$Arguments,$Schedule,$StartTime,$StartDate,$RunWithElevatedPermissions,$Days,$Interval,$Duration, $Modifier)
{

    # SCHTASKS /Create [/S system [/U username [/P [password]]]]
    #     [/RU username [/RP password]] /SC schedule [/MO modifier] [/D day]
    #     [/M months] [/I idletime] /TN taskname /TR taskrun [/ST starttime]
    #     [/RI interval] [ {/ET endtime | /DU duration} [/K] [/XML xmlfile] [/V1]]
    #     [/SD startdate] [/ED enddate] [/IT | /NP] [/Z] [/F] [/HRESULT] [/?]

    # note - /RL and /DELAY appear in the "Parameter list" for "SCHTASKS /Create /?" but not in the syntax above

    $argumentList = @();
    $argumentList += @( "/Create" );

    $argumentList += @( "/RU", "`"$RunAsUser`"" );
    
    if( -not (StringIsNullOrWhiteSpace($RunAsPassword)))
    {
    	$RAP = $RunAsPassword -Replace "`"","\`""
        $argumentList += @( "/RP `"$RAP`""  );
    }

    $argumentList += @( "/SC", $Schedule );

    if( -not (StringIsNullOrWhiteSpace($Interval)) )
    {
        $argumentList += @( "/RI", $Interval );
    }

    if( -not (StringIsNullOrWhiteSpace($Modifier)))
    {
        switch -Regex ($Schedule)
        {
            "MINUTE|HOURLY|DAILY|WEEKLY|MONTHLY|ONEVENT" {
                $argumentList += @( "/MO", $Modifier );
            }
            "ONCE|ONSTART|ONLOGON|ONIDLE" {
                $argumentList += @( "/MO" );
        }
    }
    }

    if( -not (StringIsNullOrWhiteSpace($Days)))
    {
        if($Schedule -ne "WEEKDAYS") {
            $argumentList += @( "/D", $Days );
        } else {
            $argumentList += @( "/D", "MON,TUE,WED,THU,FRI" );
        }
    }

    $argumentList += @( "/TN", "`"$TaskName`"" );

    if( $Arguments )
    {
        $argumentList += @( "/TR", "`"'$TaskRun' $Arguments`"" );
    }
    else
    {
        $argumentList += @( "/TR", "`"'$TaskRun'`"" );
    }

    if( -not (StringIsNullOrWhiteSpace($StartTime)) )
    {
        $argumentList += @( "/ST", $StartTime );
    }

    if( -not (StringIsNullOrWhiteSpace($Duration)) )
    {
        $argumentList += @( "/DU", $Duration );
    }

    if( -not (StringIsNullOrWhiteSpace($StartDate)) )
    {
        $argumentList += @( "/SD", $StartDate );
    }

    $argumentList += @( "/F" );

    if( $RunWithElevatedPermissions )
    {
        $argumentList += @( "/RL", "HIGHEST" );
    }

    Invoke-CommandLine -FilePath     "$($env:SystemRoot)\System32\schtasks.exe" `
                       -ArgumentList $argumentList;

}

Function Delete-ScheduledTask($TaskName) {
    # SCHTASKS /Delete [/S system [/U username [/P [password]]]]
    #          /TN taskname [/F] [/HRESULT] [/?]
    Invoke-CommandLine -FilePath     "$($env:SystemRoot)\System32\schtasks.exe" `
                       -ArgumentList @( "/Delete", "/S", "localhost", "/TN", "`"$TaskName`"", "/F" );
}

Function Stop-ScheduledTask($TaskName) {
    # SCHTASKS /End [/S system [/U username [/P [password]]]]
    #          /TN taskname [/HRESULT] [/?]
    Invoke-CommandLine -FilePath     "$($env:SystemRoot)\System32\schtasks.exe" `
                       -ArgumentList @( "/End", "/S", "localhost", "/TN", "`"$TaskName`"" );
}

Function Start-ScheduledTask($TaskName) {
    # SCHTASKS /Run [/S system [/U username [/P [password]]]] [/I]
    #          /TN taskname [/HRESULT] [/?]
    Invoke-CommandLine -FilePath     "$($env:SystemRoot)\System32\schtasks.exe" `
                       -ArgumentList @( "/Run", "/S", "localhost", "/TN", "`"$TaskName`"" );
}

Function Enable-ScheduledTask($TaskName) {
    # SCHTASKS /Change [/S system [/U username [/P [password]]]] /TN taskname
    #      { [/RU runasuser] [/RP runaspassword] [/TR taskrun] [/ST starttime]
    #        [/RI interval] [ {/ET endtime | /DU duration} [/K] ]
    #        [/SD startdate] [/ED enddate] [/ENABLE | /DISABLE] [/IT] [/Z] }
    #        [/HRESULT] [/?]
    Invoke-CommandLine -FilePath     "$($env:SystemRoot)\System32\schtasks.exe" `
                       -ArgumentList @( "/Change", "/S", "localhost", "/TN", "`"$TaskName`"", "/ENABLE" );
}

Function Disable-ScheduledTask($TaskName) {
    # SCHTASKS /Change [/S system [/U username [/P [password]]]] /TN taskname
    #      { [/RU runasuser] [/RP runaspassword] [/TR taskrun] [/ST starttime]
    #        [/RI interval] [ {/ET endtime | /DU duration} [/K] ]
    #        [/SD startdate] [/ED enddate] [/ENABLE | /DISABLE] [/IT] [/Z] }
    #        [/HRESULT] [/?]
    Invoke-CommandLine -FilePath     "$($env:SystemRoot)\System32\schtasks.exe" `
                       -ArgumentList @( "/Change", "/S", "localhost", "/TN", "`"$TaskName`"", "/DISABLE" );
}

Function ScheduledTask-Exists($taskName) {
   $schedule = new-object -com Schedule.Service
   $schedule.connect()
   $tasks = $schedule.getfolder("\").gettasks(0)
   foreach ($task in ($tasks | select Name)) {
      #echo "TASK: $($task.name)"
      if($task.Name -eq $taskName) {
         #write-output "$task already exists"
         return $true
      }
   }
   return $false
}

Function StringIsNullOrWhitespace([string] $string)
{
    if ($string -ne $null) { $string = $string.Trim() }
    return [string]::IsNullOrEmpty($string)
}

function Invoke-CommandLine
{
    param
    (
        [Parameter(Mandatory=$true)]
        [string] $FilePath,
        [Parameter(Mandatory=$false)]
        [string[]] $ArgumentList = @( ),
        [Parameter(Mandatory=$false)]
        [string[]] $SuccessCodes = @( 0 )
    )
    $SanitizedArgList = $ArgumentList | ForEach-Object { if($_.StartsWith("/RP")) { "/RP ********" } else { $_ } }
    Write-Host ($FilePath + " " + ($SanitizedArgList -Join " "));
    
    $process = Start-Process -FilePath $FilePath -ArgumentList $ArgumentList -Wait -NoNewWindow -PassThru;
    if( $SuccessCodes -notcontains $process.ExitCode )
    {
        throw new-object System.InvalidOperationException("process terminated with exit code '$($process.ExitCode)'.");
    }
}

function Invoke-OctopusStep
{
    param
    (
        [Parameter(Mandatory=$true)]
        [hashtable] $OctopusParameters
    )

    $taskName = $OctopusParameters['TaskName']
    $runAsUser = $OctopusParameters['RunAsUser']
    $runAsPassword = $OctopusParameters['RunAsPassword']
    $command = $OctopusParameters['Command']
    $arguments = $OctopusParameters['Arguments']
    $schedule = $OctopusParameters['Schedule']
    $startTime = $OctopusParameters['StartTime']
    $startDate = $OctopusParameters['StartDate']

    if( $OctopusParameters.ContainsKey("RunWithElevatedPermissions") )
    {
        $runWithElevatedPermissions = [boolean]::Parse($OctopusParameters['RunWithElevatedPermissions'])
    }
    else
    {
        $runWithElevatedPermissions = $false;
    }

    $days = $OctopusParameters['Days']
    $interval = $OctopusParameters['Interval']
    $duration = $OctopusParameters['Duration']
    $Modifier = $OctopusParameters['Modifier']

    if((ScheduledTask-Exists($taskName))){
        Write-Output "$taskName already exists, Tearing down..."
        Write-Output "Stopping $taskName..."
        Stop-ScheduledTask($taskName)
        Write-Output "Successfully Stopped $taskName"
        Write-Output "Deleting $taskName..."
        Delete-ScheduledTask($taskName)
        Write-Output "Successfully Deleted $taskName"
    }
    Write-Output "Creating Scheduled Task - $taskName"

    Create-ScheduledTask $taskName $runAsUser $runAsPassword $command $arguments $schedule $startTime $startDate $runWithElevatedPermissions $days $interval $duration $Modifier
    Write-Output "Successfully Created $taskName"

    if( $OctopusParameters.ContainsKey('TaskStatus') )
    {
        $taskStatus = $OctopusParameters['TaskStatus']
        if( -not (StringIsNullOrWhiteSpace($taskStatus)) )
        {
            if ( $taskStatus -eq "ENABLE" )
            {
                Enable-ScheduledTask($taskName)
                Write-Output "$taskName enabled"
            }
            elseif ( $taskStatus -eq "DISABLE" )
            {
                Disable-ScheduledTask($taskName)
                Write-Output "$taskName disabled"
            }
            else
            {
                Write-Output "$taskName status unchanged (on create, will be enabled)"
            }
        }
    }

    if( $OctopusParameters.ContainsKey("StartNewTaskNow") )
    {
        $startNewTaskNow = [boolean]::Parse($OctopusParameters['StartNewTaskNow'])
    }
    else
    {
        $startNewTaskNow = $false;
    }

    if( $startNewTaskNow ) {
      Start-ScheduledTask($taskName)
    }
}


# only execute the step if it's called from octopus deploy,
# and skip it if we're runnning inside a Pester test
if( Test-Path -Path "Variable:OctopusParameters" )
{
    Invoke-OctopusStep -OctopusParameters $OctopusParameters;
}

Provided under the Apache License version 2.0.

Report an issue

To use this template in Octopus Deploy, copy the JSON below and paste it into the Library → Step templates → Import dialog.

{
  "Id": "17bc51d1-8b88-4aad-b188-24a0904d0bf2",
  "Name": "Windows Scheduled Task - Create",
  "Description": "Create Windows scheduled task. If the task exists it will be torn down and re-added to ensure consistency",
  "Version": 22,
  "ExportedAt": "2022-03-29T11:49:45.384Z",
  "ActionType": "Octopus.Script",
  "Author": "harrisonmeister",
  "Packages": [],
  "Parameters": [
    {
      "Name": "TaskName",
      "Label": "Name",
      "HelpText": "The name of the Scheduled Task",
      "DefaultValue": null,
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Name": "RunAsUser",
      "Label": "User",
      "HelpText": "The User that the task will run as",
      "DefaultValue": "System",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Name": "RunAsPassword",
      "Label": "Password",
      "HelpText": "Specifying a password allows the task to run when the user is not logged on to the server.",
      "DefaultValue": null,
      "DisplaySettings": {
        "Octopus.ControlType": "Sensitive"
      }
    },
    {
      "Name": "Command",
      "Label": "Action",
      "HelpText": "The Action that the task executes. Usually a path to the executable",
      "DefaultValue": null,
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Name": "Arguments",
      "Label": "Arguments",
      "HelpText": "A value that specifies any arguments to be passed to run the task.",
      "DefaultValue": null,
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Name": "Schedule",
      "Label": "Schedule",
      "HelpText": "When the Task is triggered",
      "DefaultValue": "DAILY",
      "DisplaySettings": {
        "Octopus.ControlType": "Select",
        "Octopus.SelectOptions": "MINUTE|Every Minute\nHOURLY|Hourly\nDAILY|Daily\nWEEKLY|Weekly\nWEEKDAYS|Weekdays\nONCE|One off\nONSTART|On Start\nONLOGON|On Logon\nONIDLE|On Idle\nMONTHLY|Monthly"
      }
    },
    {
      "Name": "StartTime",
      "Label": "Start Time",
      "HelpText": "The Time the task will run. Use the format HH:mm:ss",
      "DefaultValue": "12:00",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Name": "StartDate",
      "Label": "Start Date",
      "HelpText": "The date the task will start running. use the format MM/dd/yyyy",
      "DefaultValue": null,
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Name": "Modifier",
      "Label": "Modifier",
      "HelpText": "A value that specifies how often the task runs within its schedule type. For ONCE, ONSTART, ONLOGON and ONIDLE any value can be used since it will be ignored (They do not use modifiers with MO).",
      "DefaultValue": null,
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Name": "Interval",
      "Label": "Interval",
      "HelpText": "A value that specifies the repetition interval in minutes.",
      "DefaultValue": null,
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Name": "Duration",
      "Label": "Duration",
      "HelpText": "A value that specifies the duration to run the task. The time format is HH:mm (24-hour time).",
      "DefaultValue": null,
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Name": "RunWithElevatedPermissions",
      "Label": "RunWithElevatedPermissions",
      "HelpText": null,
      "DefaultValue": null,
      "DisplaySettings": {
        "Octopus.ControlType": "Checkbox"
      }
    },
    {
      "Name": "Days",
      "Label": "Days",
      "HelpText": "A value that specifies the day of the week to run the task. Valid values are: MON, TUE, WED, THU, FRI, SAT, SUN and for MONTHLY schedules 1 - 31 (days of the month). The wildcard character (*) specifies all days.",
      "DefaultValue": null,
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText",
        "Octopus.SelectOptions": ""
      }
    },
    {
      "Name": "StartNewTaskNow",
      "Label": "StartNewTaskNow",
      "HelpText": null,
      "DefaultValue": "False",
      "DisplaySettings": {
        "Octopus.ControlType": "Checkbox"
      }
    },
    {
      "Name": "TaskStatus",
      "Label": "TaskStatus",
      "HelpText": "Whether the task is enabled, disabled, or left as-is when this step completes",
      "DefaultValue": "ENABLE",
      "DisplaySettings": {
        "Octopus.ControlType": "Select",
        "Octopus.SelectOptions": "ENABLE|Enable\nDISABLE|Disable\nLEAVE|Leave Unchanged"
      },
      "Links": {}
    }
  ],
  "Properties": {
    "Octopus.Action.Script.ScriptBody": "$ErrorActionPreference = \"Stop\";\nSet-StrictMode -Version \"Latest\";\n\n# use http://msdn.microsoft.com/en-us/library/windows/desktop/bb736357(v=vs.85).aspx for API reference\n\nFunction Create-ScheduledTask($TaskName,$RunAsUser,$RunAsPassword,$TaskRun,$Arguments,$Schedule,$StartTime,$StartDate,$RunWithElevatedPermissions,$Days,$Interval,$Duration, $Modifier)\n{\n\n    # SCHTASKS /Create [/S system [/U username [/P [password]]]]\n    #     [/RU username [/RP password]] /SC schedule [/MO modifier] [/D day]\n    #     [/M months] [/I idletime] /TN taskname /TR taskrun [/ST starttime]\n    #     [/RI interval] [ {/ET endtime | /DU duration} [/K] [/XML xmlfile] [/V1]]\n    #     [/SD startdate] [/ED enddate] [/IT | /NP] [/Z] [/F] [/HRESULT] [/?]\n\n    # note - /RL and /DELAY appear in the \"Parameter list\" for \"SCHTASKS /Create /?\" but not in the syntax above\n\n    $argumentList = @();\n    $argumentList += @( \"/Create\" );\n\n    $argumentList += @( \"/RU\", \"`\"$RunAsUser`\"\" );\n    \n    if( -not (StringIsNullOrWhiteSpace($RunAsPassword)))\n    {\n    \t$RAP = $RunAsPassword -Replace \"`\"\",\"\\`\"\"\n        $argumentList += @( \"/RP `\"$RAP`\"\"  );\n    }\n\n    $argumentList += @( \"/SC\", $Schedule );\n\n    if( -not (StringIsNullOrWhiteSpace($Interval)) )\n    {\n        $argumentList += @( \"/RI\", $Interval );\n    }\n\n    if( -not (StringIsNullOrWhiteSpace($Modifier)))\n    {\n        switch -Regex ($Schedule)\n        {\n            \"MINUTE|HOURLY|DAILY|WEEKLY|MONTHLY|ONEVENT\" {\n                $argumentList += @( \"/MO\", $Modifier );\n            }\n            \"ONCE|ONSTART|ONLOGON|ONIDLE\" {\n                $argumentList += @( \"/MO\" );\n        }\n    }\n    }\n\n    if( -not (StringIsNullOrWhiteSpace($Days)))\n    {\n        if($Schedule -ne \"WEEKDAYS\") {\n            $argumentList += @( \"/D\", $Days );\n        } else {\n            $argumentList += @( \"/D\", \"MON,TUE,WED,THU,FRI\" );\n        }\n    }\n\n    $argumentList += @( \"/TN\", \"`\"$TaskName`\"\" );\n\n    if( $Arguments )\n    {\n        $argumentList += @( \"/TR\", \"`\"'$TaskRun' $Arguments`\"\" );\n    }\n    else\n    {\n        $argumentList += @( \"/TR\", \"`\"'$TaskRun'`\"\" );\n    }\n\n    if( -not (StringIsNullOrWhiteSpace($StartTime)) )\n    {\n        $argumentList += @( \"/ST\", $StartTime );\n    }\n\n    if( -not (StringIsNullOrWhiteSpace($Duration)) )\n    {\n        $argumentList += @( \"/DU\", $Duration );\n    }\n\n    if( -not (StringIsNullOrWhiteSpace($StartDate)) )\n    {\n        $argumentList += @( \"/SD\", $StartDate );\n    }\n\n    $argumentList += @( \"/F\" );\n\n    if( $RunWithElevatedPermissions )\n    {\n        $argumentList += @( \"/RL\", \"HIGHEST\" );\n    }\n\n    Invoke-CommandLine -FilePath     \"$($env:SystemRoot)\\System32\\schtasks.exe\" `\n                       -ArgumentList $argumentList;\n\n}\n\nFunction Delete-ScheduledTask($TaskName) {\n    # SCHTASKS /Delete [/S system [/U username [/P [password]]]]\n    #          /TN taskname [/F] [/HRESULT] [/?]\n    Invoke-CommandLine -FilePath     \"$($env:SystemRoot)\\System32\\schtasks.exe\" `\n                       -ArgumentList @( \"/Delete\", \"/S\", \"localhost\", \"/TN\", \"`\"$TaskName`\"\", \"/F\" );\n}\n\nFunction Stop-ScheduledTask($TaskName) {\n    # SCHTASKS /End [/S system [/U username [/P [password]]]]\n    #          /TN taskname [/HRESULT] [/?]\n    Invoke-CommandLine -FilePath     \"$($env:SystemRoot)\\System32\\schtasks.exe\" `\n                       -ArgumentList @( \"/End\", \"/S\", \"localhost\", \"/TN\", \"`\"$TaskName`\"\" );\n}\n\nFunction Start-ScheduledTask($TaskName) {\n    # SCHTASKS /Run [/S system [/U username [/P [password]]]] [/I]\n    #          /TN taskname [/HRESULT] [/?]\n    Invoke-CommandLine -FilePath     \"$($env:SystemRoot)\\System32\\schtasks.exe\" `\n                       -ArgumentList @( \"/Run\", \"/S\", \"localhost\", \"/TN\", \"`\"$TaskName`\"\" );\n}\n\nFunction Enable-ScheduledTask($TaskName) {\n    # SCHTASKS /Change [/S system [/U username [/P [password]]]] /TN taskname\n    #      { [/RU runasuser] [/RP runaspassword] [/TR taskrun] [/ST starttime]\n    #        [/RI interval] [ {/ET endtime | /DU duration} [/K] ]\n    #        [/SD startdate] [/ED enddate] [/ENABLE | /DISABLE] [/IT] [/Z] }\n    #        [/HRESULT] [/?]\n    Invoke-CommandLine -FilePath     \"$($env:SystemRoot)\\System32\\schtasks.exe\" `\n                       -ArgumentList @( \"/Change\", \"/S\", \"localhost\", \"/TN\", \"`\"$TaskName`\"\", \"/ENABLE\" );\n}\n\nFunction Disable-ScheduledTask($TaskName) {\n    # SCHTASKS /Change [/S system [/U username [/P [password]]]] /TN taskname\n    #      { [/RU runasuser] [/RP runaspassword] [/TR taskrun] [/ST starttime]\n    #        [/RI interval] [ {/ET endtime | /DU duration} [/K] ]\n    #        [/SD startdate] [/ED enddate] [/ENABLE | /DISABLE] [/IT] [/Z] }\n    #        [/HRESULT] [/?]\n    Invoke-CommandLine -FilePath     \"$($env:SystemRoot)\\System32\\schtasks.exe\" `\n                       -ArgumentList @( \"/Change\", \"/S\", \"localhost\", \"/TN\", \"`\"$TaskName`\"\", \"/DISABLE\" );\n}\n\nFunction ScheduledTask-Exists($taskName) {\n   $schedule = new-object -com Schedule.Service\n   $schedule.connect()\n   $tasks = $schedule.getfolder(\"\\\").gettasks(0)\n   foreach ($task in ($tasks | select Name)) {\n      #echo \"TASK: $($task.name)\"\n      if($task.Name -eq $taskName) {\n         #write-output \"$task already exists\"\n         return $true\n      }\n   }\n   return $false\n}\n\nFunction StringIsNullOrWhitespace([string] $string)\n{\n    if ($string -ne $null) { $string = $string.Trim() }\n    return [string]::IsNullOrEmpty($string)\n}\n\nfunction Invoke-CommandLine\n{\n    param\n    (\n        [Parameter(Mandatory=$true)]\n        [string] $FilePath,\n        [Parameter(Mandatory=$false)]\n        [string[]] $ArgumentList = @( ),\n        [Parameter(Mandatory=$false)]\n        [string[]] $SuccessCodes = @( 0 )\n    )\n    $SanitizedArgList = $ArgumentList | ForEach-Object { if($_.StartsWith(\"/RP\")) { \"/RP ********\" } else { $_ } }\n    Write-Host ($FilePath + \" \" + ($SanitizedArgList -Join \" \"));\n    \n    $process = Start-Process -FilePath $FilePath -ArgumentList $ArgumentList -Wait -NoNewWindow -PassThru;\n    if( $SuccessCodes -notcontains $process.ExitCode )\n    {\n        throw new-object System.InvalidOperationException(\"process terminated with exit code '$($process.ExitCode)'.\");\n    }\n}\n\nfunction Invoke-OctopusStep\n{\n    param\n    (\n        [Parameter(Mandatory=$true)]\n        [hashtable] $OctopusParameters\n    )\n\n    $taskName = $OctopusParameters['TaskName']\n    $runAsUser = $OctopusParameters['RunAsUser']\n    $runAsPassword = $OctopusParameters['RunAsPassword']\n    $command = $OctopusParameters['Command']\n    $arguments = $OctopusParameters['Arguments']\n    $schedule = $OctopusParameters['Schedule']\n    $startTime = $OctopusParameters['StartTime']\n    $startDate = $OctopusParameters['StartDate']\n\n    if( $OctopusParameters.ContainsKey(\"RunWithElevatedPermissions\") )\n    {\n        $runWithElevatedPermissions = [boolean]::Parse($OctopusParameters['RunWithElevatedPermissions'])\n    }\n    else\n    {\n        $runWithElevatedPermissions = $false;\n    }\n\n    $days = $OctopusParameters['Days']\n    $interval = $OctopusParameters['Interval']\n    $duration = $OctopusParameters['Duration']\n    $Modifier = $OctopusParameters['Modifier']\n\n    if((ScheduledTask-Exists($taskName))){\n        Write-Output \"$taskName already exists, Tearing down...\"\n        Write-Output \"Stopping $taskName...\"\n        Stop-ScheduledTask($taskName)\n        Write-Output \"Successfully Stopped $taskName\"\n        Write-Output \"Deleting $taskName...\"\n        Delete-ScheduledTask($taskName)\n        Write-Output \"Successfully Deleted $taskName\"\n    }\n    Write-Output \"Creating Scheduled Task - $taskName\"\n\n    Create-ScheduledTask $taskName $runAsUser $runAsPassword $command $arguments $schedule $startTime $startDate $runWithElevatedPermissions $days $interval $duration $Modifier\n    Write-Output \"Successfully Created $taskName\"\n\n    if( $OctopusParameters.ContainsKey('TaskStatus') )\n    {\n        $taskStatus = $OctopusParameters['TaskStatus']\n        if( -not (StringIsNullOrWhiteSpace($taskStatus)) )\n        {\n            if ( $taskStatus -eq \"ENABLE\" )\n            {\n                Enable-ScheduledTask($taskName)\n                Write-Output \"$taskName enabled\"\n            }\n            elseif ( $taskStatus -eq \"DISABLE\" )\n            {\n                Disable-ScheduledTask($taskName)\n                Write-Output \"$taskName disabled\"\n            }\n            else\n            {\n                Write-Output \"$taskName status unchanged (on create, will be enabled)\"\n            }\n        }\n    }\n\n    if( $OctopusParameters.ContainsKey(\"StartNewTaskNow\") )\n    {\n        $startNewTaskNow = [boolean]::Parse($OctopusParameters['StartNewTaskNow'])\n    }\n    else\n    {\n        $startNewTaskNow = $false;\n    }\n\n    if( $startNewTaskNow ) {\n      Start-ScheduledTask($taskName)\n    }\n}\n\n\n# only execute the step if it's called from octopus deploy,\n# and skip it if we're runnning inside a Pester test\nif( Test-Path -Path \"Variable:OctopusParameters\" )\n{\n    Invoke-OctopusStep -OctopusParameters $OctopusParameters;\n}\n",
    "Octopus.Action.Script.Syntax": "PowerShell",
    "Octopus.Action.Script.ScriptSource": "Inline"
  },
  "Category": "Windows",
  "HistoryUrl": "https://github.com/OctopusDeploy/Library/commits/master/step-templates//opt/buildagent/work/75443764cd38076d/step-templates/windows-scheduled-task-create.json",
  "Website": "/step-templates/17bc51d1-8b88-4aad-b188-24a0904d0bf2",
  "Logo": "iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAMAAACahl6sAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADNQTFRF////Da3qSsLvhtb0wur6O7zuWcfxldv2aMzyK7ftpOD3s+X48Pr+0fD7d9HzHLLr4fX8xD/OcwAAAaNJREFUeNrs3cFygjAUQFECWott1f//2sJoW6kIKEzNs+euXOmcmSSGDa8oJEmSJEmSJGmsj1W1K9cpsGD1Vr2WdToVEPC+2lYvZfpVrEW0qZpF1F+MRdRugzoNlvkiarfBPk0pT8GhWUSX2yASpDlLr2+DEJBmEY1ug6whx7N0n2b30G1QlmmxHsRYp6X76yvF9vg5RYQczq8UVURI35UiFmTgShED0p6lI1eKzCHTrxS5Qk6PZ9PLDtJ9PIsJmXWlyAky6/dAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQMJCyjltF/iO3gpJUpD8s4OAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgID8T8itwwKyhbTdMr4ha8hXUwZqhICcOgyNOIkE+V5wo4MSgr1u/fp7poO+AL8K/gL8yw0UeyRB34m9iQ/pVD8L5JYTO3NI58R+AsiEEzsW5OfE3sUe/zRwYkeGnG2g2CPS7rhjF4GKP0ZwyoldxK37kFqEL/7wU0mSJEmSJOmJ+xRgAHxZTCXGdZkfAAAAAElFTkSuQmCC",
  "$Meta": {
    "Type": "ActionTemplate"
  }
}

History

Page updated on Tuesday, March 29, 2022