Create Scheduled Tasks From XML

Octopus.Script exported 2015-04-29 by josh3ennett belongs to ‘XML’ category.

This will create a schedule task based on exported xml. See https://msdn.microsoft.com/en-us/library/windows/desktop/bb736357%28v=vs.85%29.aspx for instructions on how to export scheduled tasks as xml.

Parameters

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

Xml File List

xmlFileName

A list of XML files, separated by ’;’, containing the scheduled tasks to create.

User Name

username

The User that the task will run as

Password

password

The password of the user the task will run as

Script body

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

# Running outside octopus
param(
    [string]$xmlFileName,
    [string]$userName,
    [string]$password
)

$ErrorActionPreference = "Stop" 

function Get-Param($Name, [switch]$Required, $Default) {
    $result = $null

    if ($OctopusParameters -ne $null) {
        $result = $OctopusParameters[$Name]
    }

    if ($result -eq $null) {
        $variable = Get-Variable $Name -EA SilentlyContinue    
        if ($variable -ne $null) {
            $result = $variable.Value
        }
    }

    if ($result -eq $null) {
        if ($Required) {
            throw "Missing parameter value $Name"
        } else {
            $result = $Default
        }
    }

    return $result
}

Function Create-ScheduledTask($xmlFileName, $taskName, $username, $password){
	$Command = "schtasks.exe /create /tn $($taskName) /RU $($username) /RP $($password) /XML $($xmlFileName)"

	Write-Host $Command
	Invoke-Expression $Command
 }

Function Delete-ScheduledTask($TaskName) {   
	$Command = "schtasks.exe /delete /tn `"$TaskName`" /F"            
	Invoke-Expression $Command 
}

Function Stop-ScheduledTask($TaskName) {  
	$Command = "schtasks.exe /end /tn `"$TaskName`""            
	Invoke-Expression $Command 
}

Function Start-ScheduledTask($TaskName) {   
	$Command = "schtasks.exe /run /tn `"$TaskName`""            
	Invoke-Expression $Command 
}

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 GetTaskNameFromXmlPath($xmlFile){
    return (Split-Path -Path $xmlFile -Leaf -Resolve).Split(".")[0]
}

& {
    param(
        [string]$xmlFileName,
        [string]$userName,
        [string]$password
    ) 

    Write-Host "Create Schedule Task From XML"
    Write-Host "xmlFileName: $xmlFileName"
    Write-Host "userName: $userName"
    Write-Host "password: <Hidden>"

    $xmlFileName.Split(";") | foreach{
        $xmlFile = $_.Trim()
        $taskName = GetTaskNameFromXmlPath($xmlFile)


        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 "Create a Scheduled Task from $xmlFile called $taskName. Run as $username" 
        Create-ScheduledTask "$($xmlFile)" $taskName $username $password
    }

}`
(Get-Param 'xmlFileName' -Required)`
(Get-Param 'userName' -Required)`
(Get-Param 'password' -Required)

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": "26c779af-4cce-447e-98bb-4741c25e0b3c",
  "Name": "Create Scheduled Tasks From XML",
  "Description": "This will create a schedule task based on exported xml. See https://msdn.microsoft.com/en-us/library/windows/desktop/bb736357%28v=vs.85%29.aspx for instructions on how to export scheduled tasks as xml.",
  "Version": 27,
  "ExportedAt": "2015-04-29T14:15:45.938+00:00",
  "ActionType": "Octopus.Script",
  "Author": "josh3ennett",
  "Parameters": [
    {
      "Name": "xmlFileName",
      "Label": "Xml File List",
      "HelpText": "A list of XML files, separated by ';', containing the scheduled tasks to create.",
      "DefaultValue": null,
      "DisplaySettings": {
        "Octopus.ControlType": "MultiLineText"
      }
    },
    {
      "Name": "username",
      "Label": "User Name",
      "HelpText": "The User that the task will run as",
      "DefaultValue": null,
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Name": "password",
      "Label": "Password",
      "HelpText": "The password of the user the task will run as",
      "DefaultValue": null,
      "DisplaySettings": {
        "Octopus.ControlType": "Sensitive"
      }
    }
  ],
  "Properties": {
    "Octopus.Action.Script.ScriptBody": "# Running outside octopus\nparam(\n    [string]$xmlFileName,\n    [string]$userName,\n    [string]$password\n)\n\n$ErrorActionPreference = \"Stop\" \n\nfunction Get-Param($Name, [switch]$Required, $Default) {\n    $result = $null\n\n    if ($OctopusParameters -ne $null) {\n        $result = $OctopusParameters[$Name]\n    }\n\n    if ($result -eq $null) {\n        $variable = Get-Variable $Name -EA SilentlyContinue    \n        if ($variable -ne $null) {\n            $result = $variable.Value\n        }\n    }\n\n    if ($result -eq $null) {\n        if ($Required) {\n            throw \"Missing parameter value $Name\"\n        } else {\n            $result = $Default\n        }\n    }\n\n    return $result\n}\n\nFunction Create-ScheduledTask($xmlFileName, $taskName, $username, $password){\n\t$Command = \"schtasks.exe /create /tn $($taskName) /RU $($username) /RP $($password) /XML $($xmlFileName)\"\n\n\tWrite-Host $Command\n\tInvoke-Expression $Command\n }\n\nFunction Delete-ScheduledTask($TaskName) {   \n\t$Command = \"schtasks.exe /delete /tn `\"$TaskName`\" /F\"            \n\tInvoke-Expression $Command \n}\n\nFunction Stop-ScheduledTask($TaskName) {  \n\t$Command = \"schtasks.exe /end /tn `\"$TaskName`\"\"            \n\tInvoke-Expression $Command \n}\n\nFunction Start-ScheduledTask($TaskName) {   \n\t$Command = \"schtasks.exe /run /tn `\"$TaskName`\"\"            \n\tInvoke-Expression $Command \n}\n\nFunction ScheduledTask-Exists($taskName) {\n   $schedule = new-object -com Schedule.Service \n   $schedule.connect() \n   $tasks = $schedule.getfolder(\"\\\").gettasks(0)\n\n   foreach ($task in ($tasks | select Name)) {\n\t  #echo \"TASK: $($task.name)\"\n\t  if($task.Name -eq $taskName) {\n\t\t #write-output \"$task already exists\"\n\t\t return $true\n\t  }\n   }\n\n   return $false\n}\n\nFunction GetTaskNameFromXmlPath($xmlFile){\n    return (Split-Path -Path $xmlFile -Leaf -Resolve).Split(\".\")[0]\n}\n\n& {\n    param(\n        [string]$xmlFileName,\n        [string]$userName,\n        [string]$password\n    ) \n\n    Write-Host \"Create Schedule Task From XML\"\n    Write-Host \"xmlFileName: $xmlFileName\"\n    Write-Host \"userName: $userName\"\n    Write-Host \"password: <Hidden>\"\n\n    $xmlFileName.Split(\";\") | foreach{\n        $xmlFile = $_.Trim()\n        $taskName = GetTaskNameFromXmlPath($xmlFile)\n\n\n        if((ScheduledTask-Exists($taskName))){\n\t        Write-Output \"$taskName already exists, Tearing down...\"\n\t        Write-Output \"Stopping $taskName...\"\n\t        Stop-ScheduledTask($taskName)\n\t        Write-Output \"Successfully Stopped $taskName\"\n\t        Write-Output \"Deleting $taskName...\"\n\t        Delete-ScheduledTask($taskName)\n\t        Write-Output \"Successfully Deleted $taskName\"\n        }\n\n        Write-Output \"Create a Scheduled Task from $xmlFile called $taskName. Run as $username\" \n        Create-ScheduledTask \"$($xmlFile)\" $taskName $username $password\n    }\n\n}`\n(Get-Param 'xmlFileName' -Required)`\n(Get-Param 'userName' -Required)`\n(Get-Param 'password' -Required)",
    "Octopus.Action.Script.Syntax": "PowerShell"
  },
  "Category": "XML",
  "HistoryUrl": "https://github.com/OctopusDeploy/Library/commits/master/step-templates//opt/buildagent/work/75443764cd38076d/step-templates/scheduled-task-create-from-xml.json",
  "Website": "/step-templates/26c779af-4cce-447e-98bb-4741c25e0b3c",
  "Logo": "iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAIAAAAiOjnJAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAACOlJREFUeNrsnc1TE2cYwNVhhnAinDb0QAIHsTBDsM4AVSvUj2qtDE6njh60emhr/512pnetPejQ6ehgrYxfBGurzlDBGZF4wMQDSU4kNzjRR2Ip7ru7+XoT8m5+v+MGdpN3f3me5/3abF9bW9sGoJsdNA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u66HW1iRSJhz56gQ/Iqcmmo2ybV8hKi45hC3eZB71atZ7avra3pOtfVa+Px+CvKC41c/O6bUMjSdbap2HQs9tDt1eHhT0aGD9Rj8d4f7UMFjViWpdEqg3uFu3Z1t7a2IoQuhoYM/l0dzcMNx44eQQhd4croDKBZLAla3d070aJyTP+pph3VaBHLsjCjEsbGRs2trqolViAQELeam5vxozwGBwd80A2qypSOfNu+v/gtcau8WOWPOrVac4XBYOuF82cH/fJ7oTVAOtTnvz7rmyGbKq5ukJwoX75d3TunYtP8aIW3Uv39fRoHJ30uVp5IJHwhci6bzS3E4wsLcQzbPKAgNYN88aQr7b9PV6P1WJIZhwYHNn5JO53OeDxk5vbkHY8H5x89eiRkePUmPvn+qRBNW9WynjnUq0cpVpk7Nds47KAJALEAsQCxABALEAsQCwCxALEAsQAQCxALEAsAsQCxALEAtNBk3Du+/PMv3DYiFiAWAGIBYgFiQQOjd1NdPYrlyw2cBogVCvldrO5uHlZTY8LhjmCw1ediySc8duwz3KoZlmWdOX1K7zl1PjVZL9lsbio2nUgkc7kc9756gSoSCQ8NDmjf8l+/YgG9QgDEAsQCxAJALEAsQCwAxALEAsQCQCxALEAsAMQCxALEAkAsQCxALEAsAMQCU/hXgAEAvqSVJBhJrL4AAAAASUVORK5CYII=",
  "$Meta": {
    "Type": "ActionTemplate"
  }
}

History

Page updated on Wednesday, April 29, 2015