How to restart the disabled Scheduled tasks using CLI/PowerShell script? - powershell

I have deployed Scheduled tasks through the Azure DevOps pipelines. Before deploying the Scheduled tasks, I am first stopping all the Scheduled tasks, and after deployment, I will enable all the Scheduled tasks. After enabling all the Scheduled tasks, a few of the scheduled services were disabled automatically.
$taskService = Get-Process test.ScheduledTasks.Service -ErrorAction SilentlyContinue
if ($taskService) {
Stop-Process -name test.ScheduledTasks.Service -Force
}
schtasks.exe /CHANGE /TN "testtask" /DISABLE
#Enable Tasks
schtasks.exe /CHANGE /TN "testtask" /ENABLE
How to restart the disabled Scheduled tasks using CLI/PowerShell script?

Related

Schedule a Task to delete another task

I have a scheduled task in EC2 windows server 2019 that runs on start and I would like to delete after it finishes.
I tried to schedule a task to delete it but the task kept running without deleting the other one, but the scripts work from Powershell directly.
SCHTASKS /Delete /TN AfterRestartSetup /F
I tried to add /z to delete the task right after it is done but it did not work.
schtasks /create /tn "AfterRestartSetup" /sc onstart /z /rl highest /ru system /tr "powershell.exe -file C:\scripts\setup\AfterRestartSetup.ps1"
I also tried to unregister but it didn't work also:
Unregister-ScheduledTask -TaskName "AfterRestartSetup" -Confirm:$false
You can disable a task like this:
Disable-ScheduledTask -TaskPath "\your-user\" -TaskName "your-task-name"
Add the above line to a text file and save it with ps1 extension. Then create a task on Task Scheduler. In the General tab (of properties window), make sure you check Run with highest privileges. The Action should be Start a program where the Program/script is Powershell.exe and the argument has a complete path to the ps1 file you created earlier (e.g. C:\Scripts\myTask.ps1).

How to run a scheduled task in task scheduler through powers shell command

Any Powershell cmdlet to run scheduled task in task scheduler?
We have commands to Disable,Enable,Start,Stop the tasks in task schduler through powershell commands like below.But I didnt find any command to run a scheduled task which is in "Ready" state.Any idea?
Get-ScheduledTask -Taskpath "\TasksFolder\"|enable-ScheduledTask
Get-ScheduledTask -Taskpath "\TasksFolder\"|disble-ScheduledTask
Get-ScheduledTask -Taskpath "\TasksFolder\"|start-ScheduledTask
Get-ScheduledTask -Taskpath "\TasksFolder\"|stop-ScheduledTask
Use the following cmdlet to start a scheduled task from powershell:
Start-ScheduledTask -TaskPath "your task path" -TaskName "your task name"
To stop:
Stop-ScheduledTask -TaskPath "your task path" -TaskName "your task name"

How can a PowerShell script be automatically run on startup?

I want to run my script at boot up time in windows 7
I tried
Setup a scheduled task to run at startup - it doesn't run until someone logs in.
Local GP to run script at startup - it doesn't run until someone logs in.
Adding the scheduled task from a command prompt with admin - some time work some time not
schtasks /create /tn "start" /sc onstart /delay 0000:30 /rl highest /ru system /tr "powershell.exe -file <>
any other method to this ?
you can make an bat file in your startup folder.
startup.bat whit this content
Powershell -command "& {c:\Temp\Test.ps1}"

Unable to resume a workflow via task scheduler

In a powershell window I run the following workflow:
workflow foo { Suspend-Workflow; "hello world" | Out-File c:\users\weijgerss\desktop\foo.txt }
Then to resume the workflow, I have the following scheduled via task scheduler triggered to run at startup:
Import-Module PSWorkflow
$jobs = Get-Job -state Suspended
$jobs > c:\users\weijgerss\desktop\zqqfff.txt
$resumedJobs = $jobs | resume-job -wait
$resumedJobs | wait-job
# Task scheduler action: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle Normal -NoLogo -NoProfile -Command "&'c:\users\weijgerss\desktop\resume.ps1'"
The workflow does not get resumed neither at startup, nor if I manually trigger it via Task Scheduler. The contents of zqqfff.txt indicates that the task scheduler activated powershell cannot see the workflow. A regular powershell window can see the workflow when I run Get-Job.
(Both the normal powershell window and the task scheduler powershell instance run as same user.)
I used procmon to see what's going on and I can see from this that when powershell normally vs taskscheduler it's looking at different workflow persistence paths, namely:
C:\Users\weijgerss\AppData\Local\microsoft\windows\PowerShell\WF\PS\default\S-1-5-21-3519956147-933941082-741972881-500_EL (a normal powershell window uses this folder)
C:\Users\weijgerss\AppData\Local\microsoft\windows\PowerShell\WF\PS\default\S-1-5-21-3519956147-933941082-741972881-500_EL_NI (a task scheduler activated powershell instance uses this folder)
I'm totally stumped. How can I get a task scheduler activated powershell instance to see the same workflows as normal powershell window can?
The below scripts give you a solution that automatically resumes powershell workflows after a reboot/crash using task scheduler at system start up:
resume-workflows.ps1: (the first line below fixes the _NI issue mentioned in the question)
[System.Management.Automation.Remoting.PSSessionConfigurationData]::IsServerManager = $true
Import-Module PSWorkflow
Get-Job -State Suspended | Resume-Job -Wait| Wait-Job
resume-workflows.cmd: (works around a windows 8/server 2012 task scheduler bug)
#rem This is a workaround for task scheduler bug
#rem See: http://support.microsoft.com/kb/2968540
set "USERPROFILE=%USERPROFILE%\..\%USERNAME%"
set "APPDATA=%USERPROFILE%\AppData\Roaming"
set "LOCALAPPDATA=%USERPROFILE%\AppData\Local"
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NonInteractive -WindowStyle Normal -NoLogo -NoProfile -Command "&'c:\path\to\resume-workflows.ps1'"
To put it all together use the following powershell script to shedule resume-workflows.cmd to run at system start up:
$trigger = New-ScheduledTaskTrigger -AtStartup
$action = New-ScheduledTaskAction -Execute "c:\path\to\resume-workflows.cmd"
$currentuser = ([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)
Register-ScheduledTask -TaskName "Resume $($currentuser.Replace('\', '-'))'s Powershell Workflows" `
-Trigger $trigger -Action $action -RunLevel Highest -User $currentuser `
-Password (Read-Host "Enter password for $currentuser")
Enjoy!
(ILSpy, sysinternal's procmon, plenty of google and a dash of windbg were all instrumental in bringing the above answer to you)

running powershell scripts as scheduled tasks

I got a couple of scripts which perform mailboxes moves to the cloud on office 365. The scripts sometimes fails and others not, I don't have any clue on why it
fails but I guess it is because the service is not available when the task is executed, anyways, the point is that these scripts are running as scheduled tasks and one must be
executed before of other, how I could detect if the first tasks failed and if so then reschedule the second task.
The tasks are running powershell v2 cmdlets on windows 2008 r2 so I'm using Task Scheduler.
I wonder if I should save some entries into a text file, to use a different task scheduler or maybe run each job using powershell, in the following way:
foreach ($script in $scripts)
{
#check status in a text file
$job = start-job -Filepath c:\myscript.ps1 -AsJob
Wait-Job $job -Timeout 180
}
What would be the best approach?
Thanks,
You can use schtasks.exe to query / enable or reschedule your tasks. Or you can use the COM object of the scheduler (beware schtasks output is language dependant). With one or other method check the lastTaskResult and reschedule or not your other task.
Examples:
Get all tasks of the root folder using COM object
icm -AsJob -JobName getTasks -ComputerName $computername -ScriptBlock{
$Schedule = new-object -com("Schedule.Service")
$Schedule.connect($env:computername)
$Tasks = $Schedule.getfolder("\").gettasks(0)
$Tasks | Select-Object Name,Path,State,Enabled,LastRunTime,LastTaskResult
}
Get a particular task with schtasks
schtasks /query /TN "\Microsoft\Windows\Autochk\Proxy" /v /fo csv |ConvertFrom-Csv