Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Can we configure/schedule a Windows Job in Octopus Deploy?
I want to schedule windows jobs in Octopus Deploy. My main objective is to automate these jobs and reduce the amount of human intervention.
Is there any way to configure windows jobs in Octopus Deploy?
I've tried to search the Octopus library but I'm unable to implement some of the libraries I've found.
If you package this script inside your NuGet package and call it Deploy.ps1, it should run a custom deployment that will bootstrap the schtasks.exe.
Deploy.ps1
# -------------------------------------------------
# Octopus Powershell For Installing Scheduled Tasks
# -------------------------------------------------
#
# Ver Who When What
# 1.0 Evolve Software Ltd 17-05-16 Initial Version
# Script Input Parameters
# $TaskName - The name of the task that we use to create / remove
# $TaskExecutableName - the scheduled task executeable name
# $TaskSchedule - MINUTE, HOURLY, DAILY, WEEKLY, MONTHLY, ONCE, ONSTART, ONLOGON, ONIDLE
# $TaskModifier - Specifies how frequently the task runs in its schedule type. This parameter is required for a MONTHLY schedule
# $TaskStartTime - StartTime Specifies the time of day that the task starts in HH:MM:SS 24-hour format. The default value is the current local
# $TaskDisable - Disable the task after it's installed
# Script Version
$CurrentScriptVersion = "1.0"
function Main()
{
Write-Host "================== Installing Scheduled Tasks - Version"$CurrentScriptVersion": START =================="
# Log input variables passed in
Log-Variables
Write-Host
# Tear down any existing stuff
Delete-Scheduled-Task $TaskName
# Create scheduled task
$TaskPath = $OctopusOriginalPackageDirectoryPath + "\" + $TaskExecutableName
Create-Scheduled-Task $TaskName $TaskPath $TaskSchedule $TaskModifier $TaskStartTime $TaskDisable
Write-Host "================== Installing Scheduled Tasks - Version"$CurrentScriptVersion": END =================="
}
function Log-Variables
{
Write-Host "TaskName" $TaskName
Write-Host "TaskExecutableName" $TaskExecutableName
Write-Host "TaskSchedule" $TaskSchedule
Write-Host "TaskModifier" $TaskModifier
Write-Host "TaskStartTime" $TaskStartTime
Write-Host "TaskDisable" $TaskDisable
Write-Host "Computername" (gc env:computername)
}
function Create-Scheduled-Task($taskName, $taskPath, $taskSchedule, $taskModifier, $taskStartTime, $taskDisable)
{
# https://msdn.microsoft.com/en-us/library/windows/desktop/bb736357%28v=vs.85%29.aspx
Write-Host "Creating task" $taskName
Write-Host "Task path" $taskPath
Write-Host "Task schedule" $taskSchedule
Write-Host "Task modifier" $taskModifier
Write-Host "Task start time" $taskStartTime
Write-Host "Task disable" $taskDisable
if($taskModifier)
{
Write-Host "Cmd: schtasks.exe /Create /TN "$taskName" /SC "$taskSchedule" /MO "$taskModifier" /ST "$taskStartTime" /RL highest /TR "$taskPath" /RU SYSTEM"
#schtasks.exe /Create /TN $taskName /SC MINUTE /MO 5 /ST 00:00 /RL highest /TR $taskPath /RU SYSTEM
schtasks.exe /Create /TN $taskName /SC $taskSchedule /MO $taskModifier /ST $taskStartTime /RL highest /TR $taskPath /RU SYSTEM
}
else
{
Write-Host "Cmd: schtasks.exe /Create /TN "$taskName" /SC "$taskSchedule" /ST "$taskStartTime" /RL highest /TR "$taskPath" /RU SYSTEM"
#schtasks.exe /Create /TN $taskName /SC DAILY /ST 03:00:00 /RL highest /TR $taskPath /RU SYSTEM
schtasks.exe /Create /TN $taskName /SC $taskSchedule /ST $taskStartTime /RL highest /TR $taskPath /RU SYSTEM
}
if (IsTrue($taskDisable)) {
Write-Host "Disabling task: schtasks.exe /Change /TN $taskName /DISABLE"
schtasks.exe /Change /TN $taskName /DISABLE
Write-Host "Task disabled"
}
}
function Delete-Scheduled-Task($taskName)
{
# Stop Scheduled Task
Write-Host "Stopping task:" $taskName
try
{
schtasks.exe /end /TN $taskName
}
catch [System.Exception]
{
Write-Output $_
Write-Host "Unable to end task - may not exist"
}
# Wait for it to stop
while($true){
$i++
$status = schtasks /query | select-string -patt $taskName
if(!$status)
{
Write-Host "Task not running"
break
}
if($status.ToString().Contains("Running")) {
Write-Host "Task still running: "$status.ToString() -foreground red
} else {
Write-Host "Task has ended: "$status.ToString()
break
}
if($i -ge 60) # If task takes longer than 1 minute to stop bomb out
{
throw "ERROR: Unable to end task, please end it manually then kick of the deployment again"
return -1
}
Start-Sleep -s 1
}
# Remove Scheduled Task (force delete)
Write-Host "Deleting task:" $taskName
schtasks.exe /delete /TN $taskName /F
}
function IsTrue( $boolString )
{
if($boolString) #not null or not empty string
{
if($boolString -is [bool])
{
return $boolString
}
elseif($boolString -is [string])
{
if(($boolString -eq "true") -or ($boolString -eq "True") -or ($boolString -eq "1"))
{
return $true
}
}
elseif ($boolString -is [int])
{
if($boolString -eq 1)
{
return $true
}
}
}
return $false
}
Main
You can now setup some variables to configure your scheduled task such as these.
Hope this helps.
Related
I would like to have a PowerShell Script to check the task scheduler. If the task name exists then delete it.
if (schtasks /query /tn "mytask") {
schtasks /delete /tn "mytask" /f | Out-Null
}
The syntax works well when the user has the task name in the task scheduler. However, the PowerShell returns the error message when the task name doesn't exist:
schtasks : ERROR: The system cannot find the file specified.
At line:1 char:5
+ if (schtasks /query /tn "mytask") {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (ERROR: The syst...file specified.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
Is there any way to avoid or hide the PS return the error message?
I am very new to PowerShell, any help is appreciated!
You can use the stream redirection operator > to supress errors from schtasks:
if(schtasks /query /tn "mytask" 2>$null){
schtasks /delete /tn "mytask" /f | Out-Null
}
But I would personally prefer using Get-ScheduledTask from the ScheduledTasks module, then use the -ErrorAction common parameter to ignore any errors:
if(Get-ScheduledTask -TaskName "mytask" -ErrorAction Ignore){
Unregister-ScheduledTask -TaskName "mytask" -Confirm:$false | Out-Null
}
I run the following command in PowerShell:
Schtasks /create /tn "Scheduler Test4" /sc minute /tr "PowerShell -command cp c:\Users\myUsername\Desktop\myCat/main.txt c:/Users/myUsername/Desktop/myCat_backup/"
It doesn't work. I desire that main.txt gets copied into the backup directory. When I look in myCat_backup/ there is no main.txt, even if I remove the -command flag. Please help.
This script will create a sheduled task that runs powershell every minute as the user "System":
$Action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NonInteractive -NoLogo -NoProfile -command Copy-Item C:\temp\Source\main.txt C:\temp\Target\'
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 1)
$Settings = New-ScheduledTaskSettingsSet
$Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Settings $Settings
Register-ScheduledTask -TaskName 'Scheduler Test' -InputObject $Task -User 'system'
It turns out once I restarted my device, the script started working. Furthermore, I can now create more tasks and Powershell is recognizing the commands created using Schtasks without restarting.
I have a schedule task i.e mytask on 50of my computers(windows) and i am working on writing a batch file to delay the task by 2 min on all 50 computers, is this the right way to go about it ? I come across this on microsoft website.
schtasks /Change
[/S system [/U system [/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] }
You can use Powershell jobs in combination with PowerShell remoting. Some pseudo code:
$session = New-PSSession -Computer "yourComputerNameOrIp" -Credential (Get-Credential)
Invoke-Command -Session $session -Scriptblock { Write-Host "$($env:COMPUTERNAME)"
Here you'll also find a description of how to enable Powershell remoting.
Hope that helps.
To ease some of my work I have created a powershell script which needs to :
Run at startup.
Run with admin rights as it has to write in c:\program files folder.
I created the startup service using powershell like this :
function MakeStartupService
{
Write-Host "Adding script as a startup service"
$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:15
Try
{
Register-ScheduledJob -Trigger $trigger -FilePath "absolute_path" -Name "Job-name" -EA Stop
}
Catch [system.exception]
{
Write-Host "Looks like an existing startup service exists for the same. Overwriting existing job"
Unregister-ScheduledJob "Job-name"
Register-ScheduledJob -Trigger $trigger -FilePath "absolute_path" -Name "Job-name"
}
}
The job is registered as a startup service successfully and is visible inside task scheduler. If I start it using Start-Job -DefinitionName Job-name or by right clicking from Task Scheduler, it works fine but it doesn't start when windows starts.
Currently I am testing this on my personal Windows 10 system, and have checked in another windows 10 system but the behavior remained name. I am attaching screenshot of task scheduler window for this job.
Sorry if this questions sounds repeated or dumb (I am a beginner in powershell), but believe me, none of the solutions I found online worked for this.
Thanks in advance !!
This is code that is already in production that I use. If it does not work for you, you must have something else going on with your system.
function Invoke-PrepareScheduledTask
{
$taskName = "UCM_MSSQL"
$task = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
if ($task -ne $null)
{
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false
}
# TODO: EDIT THIS STUFF AS NEEDED...
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-File "C:\Invoke-MYSCRIPT.ps1"'
$trigger = New-ScheduledTaskTrigger -AtStartup -RandomDelay 00:00:30
$settings = New-ScheduledTaskSettingsSet -Compatibility Win8
$principal = New-ScheduledTaskPrincipal -UserId SYSTEM -LogonType ServiceAccount -RunLevel Highest
$definition = New-ScheduledTask -Action $action -Principal $principal -Trigger $trigger -Settings $settings -Description "Run $($taskName) at startup"
Register-ScheduledTask -TaskName $taskName -InputObject $definition
$task = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
# TODO: LOG AS NEEDED...
if ($task -ne $null)
{
Write-Output "Created scheduled task: '$($task.ToString())'."
}
else
{
Write-Output "Created scheduled task: FAILED."
}
}
If it works, it's not a script problem. Assign it to the SYSTEM account or make a separate service account instead of the Gagan account shown. Make sure that service account has "Permission to run as batch job" in your local security policy.
If you want to get rid of that "on battery" crap, add
-DontStopIfGoingOnBatteries -AllowStartIfOnBatteries
to New-ScheduledTaskSettingsSet options.
So, in Kory Gill answer, $settings becomes:
$settings = New-ScheduledTaskSettingsSet -Compatibility Win8 -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries
so task will be created to get rid of battery restrictions.
If you just want to modify an existing task, you can do it with:
Set-ScheduledTask -taskname "taskName" -settings $(New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries)
or from cmd:
powershell -executionpolicy bypass Set-ScheduledTask -taskname "taskName" -settings $(New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries)
Please check the checkbox for "Run with highest privileges" for the task in the task scheduler and try again. Currently in the screenshot above it is unchecked.
I have circled it below in red for your easy reference:
Windows schtasks.exe:
What is the equivalent command line switch for ExecutionTimeLimit in schtasks. In the Edit Tasks dialog it is "Stop tasks if it runs longer than".
I tried /ET end time and /DU duration but they imply a repetition. I only want a task to run once and then be killed x minutes later.
Not a perfect solution , but you can use /XML option of schtasks
schtasks /Create /tn jobname /XML Path_of_xml
Within the xml file you should able to use ExecutionTimeLimit to specify the time you want to kill the job .
You can get sample xml by export a exist job to get reference
schtasks /Query /tn jobname /XML > Path_of_xml
Using the Powershell it is possible to create a task where you can modify ExecutionTimeLimit to your value.
$MyPathToFile = 'C:\Path\File.exe'
$hour = '20:00:00'
$user = 'MyDomain\MyUserName'
$password = '123321Password'
$MyTask = 'MyTask'
$MyExecutionTimeLimit = '01:00:00' # HH:MM:SS
$trigger = New-ScheduledTaskTrigger -Daily -At $hour
$action = New-ScheduledTaskAction -Execute $MyPathToFile
$settingsSet = New-ScheduledTaskSettingsSet -ExecutionTimeLimit $MyExecutionTimeLimit
$task = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settingsSet
Register-ScheduledTask -TaskName $MyTask -InputObject $task -User $user -Password $password