Disable multiple scheduled tasks - PowerShell - windows

I'm working on a script that disables multiple Scheduled Tasks in Windows 10. This is my attempt:
$TasksToDisable = #(
""
""
""
)
Foreach ($Task in $TasksToDisable) {
Get-ScheduledTask $Task | Disable-ScheduledTask
}
It gives me an error when a scheduled task does not exist.
How to solve this? (without SilentlyContinue)
Thank you! :D

Your code is missing the -TaskPath or -TaskName
Example -TaskName
Disable-ScheduledTask -TaskName "SystemScan"
Example -TaskPath
Get-ScheduledTask -TaskPath "\UpdateTasks\" | Disable-ScheduledTask
Microsoft Disable-ScheduledTask Webpage
https://learn.microsoft.com/en-us/powershell/module/scheduledtasks/disable-scheduledtask?view=windowsserver2019-ps
Maybe your hash list of names is missing slashes in-between.
Example Get-ScheduledTask -TaskPath List
$tasks = Get-ScheduledTask | Select TaskPath | Where {($_.TaskPath -like "*Active Directory Rights Management Services Client*")}
$tasks
ForEach($task in $tasks){
Get-ScheduledTask -TaskPath "$task" | Disable-ScheduledTask
}
Example Get-ScheduledTask -TaskName List
$tasks = Get-ScheduledTask | Select TaskName | Where {($_.TaskName -like "*AD*")}
$tasks
ForEach($task in $tasks){
Disable-ScheduledTask -TaskName "$task"
}

Related

Getting List of Installed Applications that Matches Add/Remove Programs List

I'm working on an application that lists all of the installed programs on a customer's computer. I've been able to get a list based on registry keys, but it doesn't include things that were installed via the Microsoft Store. It looks like using PowerShell (based on the guidance on this page: https://mhelp.pro/how-to-uninstall-windows-apps/) I can get lists of installed applications, but what I'm getting there seems to include a lot of items that aren't in Add/Remove Programs, and I'm not sure how to reconcile the 2 sources (Add/Remove Programs and the lists of programs via PowerShell). Is there some better way I should be doing this, or is there a flag or criteria that I should be using to determine if a listed application is present in Add/Remove Programs?
Perhaps something like that did you mean ?
Refer to How to Create a List of Your Installed Programs on Windows
$outputFile = "$env:APPDATA\Installed_Applications.txt"
$OS_Architecture = $env:PROCESSOR_ARCHITECTURE
if($OS_Architecture -eq 'x86')
{
#write-host '32-bit'
$key = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*"
}
else
{
#write-host '64-bit'
$key = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
}
Get-ItemProperty $Key |
Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |
Format-Table –AutoSize |
Out-File $outputFile -Encoding UTF8 -Force
Start-Process $outputFile
EDIT : 25/08/2020 # 18:20
Here is a Self-elevate script to get everything with admin rights :
cls
# Self-elevate the script if required
if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) {
#$CommandLine = "-File `"" + $MyInvocation.MyCommand.Path + "`" " + $MyInvocation.UnboundArguments
$CommandLine = $MyInvocation.InvocationName
Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList $CommandLine
Exit
}
}
$outputFile = "$env:APPDATA\Installed_Applications.txt"
$OS_Architecture = $env:PROCESSOR_ARCHITECTURE
if($OS_Architecture -eq 'x86')
{
#write-host '32-bit'
$key = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*"
}
else
{
#write-host '64-bit'
$key = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
}
Get-ItemProperty $Key |
Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |
Format-Table –AutoSize | Out-String -Width 300 |
Out-File $outputFile -Encoding UTF8 -Force
Get-AppxPackage -AllUsers |
Out-File -Append $outputFile -Encoding UTF8 -Force
Start $outputFile
In powershell 5 but not powershell 7:
get-package

Create a scheduled task which runs every minute without the user being logged in using PowerShell

I'm trying to use PowerShell to create (and replace) a scheduled Windows task. I found the docs for the relevant PowerShell commands and as far as I can see, I have everything right:
$action = New-ScheduledTaskAction -Execute "node" -Argument "C:/scripts/task.js"
$now = Get-Date
$interval = New-TimeSpan -Seconds 60
$forever = [System.TimeSpan]::MaxValue
$trigger = New-ScheduledTaskTrigger -Once -At $now -RepetitionInterval $interval -RepetitionDuration $forever
$settings = New-ScheduledTaskSettingsSet
$task = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings
Register-ScheduledTask -TaskName 'TEST' -InputObject $task
However, running this, I get a cryptic error:
Register-ScheduledTask : The task XML contains a value which is incorrectly formatted or out of range.
The error message is useless - how do I debug it?
What XML? At what path?
Which value?
What range?
This answer says to now use TimeSpan.MaxValue so I used a 100 years instead:
$forever = $now.AddYears(100) - $now # [System.TimeSpan]::MaxValue doesn't work
However, the error remains the same.
I googled around and found a suggestion to look into HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree, however, my task doesn't appear in there.
What to do?
Just don't set the -RepetitionDuration parameter at all.
By default, it will do it indefinitely.
$action = New-ScheduledTaskAction -Execute "node" -Argument "C:/scripts/task.js"
$now = Get-Date
$interval = New-TimeSpan -Seconds 60
$forever = [System.TimeSpan]::MaxValue
$trigger = New-ScheduledTaskTrigger -Once -At $now -RepetitionInterval $interval
$settings = New-ScheduledTaskSettingsSet
$task = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings
Register-ScheduledTask -TaskName 'TEST' -InputObject $task
Task created using the script above
As for your error, the complete error I had when attempting to execute your script was clear enough. It specifically indicated that the "Max" timespan was not an accepted value.
Register-ScheduledTask : The task XML contains a value which is
incorrectly formatted or out of range.
(8,42):Duration:P99999999DT23H59M59S At line:8 char:1
+ Register-ScheduledTask -TaskName 'TEST' -InputObject $task
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (PS_ScheduledTask:Root/Microsoft/...S_ScheduledTask)
[Register-ScheduledTask], CimException
+ FullyQualifiedErrorId : HRESULT 0x80041318,Register-ScheduledTask

Trigger a job from Powershell

I would like to know how to create a task scheduler job from powershell for the following scenario.
The script runs between the hours of 6 AM and 9 PM Monday through Friday where the script will terminate if it runs longer than 30 minutes.
I have tried
$adminname=''
$adminpassword=''
$taskName = ""
$L = New-ScheduledTaskAction –Execute "PowerShell.exe" -Argument ''
$T = New-ScheduledTaskTrigger -Daily -At 06:30Pm -DaysOfWeek 'Monday', 'Tuesday', 'Wednesday','Thursday','Friday'
$P = New-ScheduledTaskPrincipal -UserId "" -LogonType Password -RunLevel Highest
$S = New-ScheduledTaskSettingsSet
Register-ScheduledTask -TaskName $taskName -Action $L -Trigger $T -User $adminname -Password $adminpassword -Settings $S
$task = get-scheduledtask -TaskName $taskName
$task.Triggers.repetition.Interval = 'PT15M'
$task | Set-ScheduledTask -User $adminname -Password $adminpassword
The above code schedules the job from monday to friday. But could not get a way to apply the time stamp i.e to be run between 6AM to 9PM
I have tried adding $task.Triggers.ExecutionTimeLimit = 'PT30M for terminating job if it runs longer than 30 minutes. But its giving The property 'ExecutionTimeLimit' cannot be found on this object. Verify that the property exists and can be set. error
New-ScheduledTaskAction : Sets What you want to run
New-ScheduledTaskTrigger : Set How often and when to start the run
Register-ScheduledTask : Create the Task
[TASK].Triggers.Repetition.Duration : How long the task time should run from start time
[TASK].Triggers.Repetition.Interval : How long the task should run before its killed
{PK means Pickup Time, Use PK for H(hours) M(Minutes) use P for Pickup for D(Days) Ex PK15H, P5D}
[TASK] | Set-ScheduledTask : Enable Task
$action = New-ScheduledTaskAction -Execute Powershell.exe
$trigger = New-ScheduledTaskTrigger -Weekly -At 6:30AM -DaysOfWeek 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'
$task = Register-ScheduledTask -TaskName "TESTTASK" -Trigger $trigger -Action $action -RunLevel Highest
$task.Triggers.Repetition.Duration = "PT15H"
$task.Triggers.Repetition.Interval = "PT15M"
$task | Set-ScheduledTask -User "USERNAME" -Password "PASSWORD"

Register-ScheduledJob as the system account (without having to pass in credentials)

I believe for Register-ScheduledTask you can specify -User "System"or do something like:
$principal = New-ScheduledTaskPrincipal -UserId SYSTEM -LogonType ServiceAccount -RunLevel Highest
How do I do this with Register-ScheduledJob?
This command will be running the context of the local admin so it will have access to do this. I just don't see this option in the cmdlet.
Here is an example of how to do this with the scheduled tasks cmdlet
edit: Does windows make this impossible by design? If I open an interactive PS session as the system (using psexec) and try to create a schedualed job I get an error:
PS C:\Windows\system32> Register-ScheduledJob -Name systemsssss -ScriptBlock {'s
dfsdfsdfsd'}
Register-ScheduledJob : An error occurred while registering scheduled job
definition systemsssss to the Windows Task Scheduler. The Task Scheduler
error is: (32,4):UserId:.
At line:1 char:1
+ Register-ScheduledJob -Name systemsssss -ScriptBlock {'sdfsdfsdfsd'}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Microsoft.Power...edJobDefini
tion:ScheduledJobDefinition) [Register-ScheduledJob], ScheduledJobExceptio
n
+ FullyQualifiedErrorId : CantRegisterScheduledJobDefinition,Microsoft.Pow
erShell.ScheduledJob.RegisterScheduledJobCommand
This same command works fine when run as the local administrator account
First use Register-ScheduledJob to create your PowerShell job.
Then use Set-ScheduledTask to change a startup account to the Local System or any other built-in accounts, i.e. SYSTEM, LOCAL SERVICE, NETWORK SERVICE, etc.
Use the following PS-script. Or download it from my GitHub Gist
The code is self-explanatory (I believe).
You can run it multiple times under an administrative account if you want to check how it works.
BTW, I prefer to use jobs (Register-ScheduledJob) over tasks because jobs allow me to embed PowerShell script blocks (strings) instead using of external script files. Look at -ScriptBlock below.
Also pay attention to -RunElevated. It is a must be.
$ErrorActionPreference = 'Stop'
Clear-Host
#### Start of Main Logic ###########################
$taskName = "my_PowerShell_job"
$accountId = "NT AUTHORITY\SYSTEM";
#$accountId = "NT AUTHORITY\LOCAL SERVICE";
$task = Get-ScheduledJob -Name $taskName -ErrorAction SilentlyContinue
if ($task -ne $null)
{
Unregister-ScheduledJob $task -Confirm:$false
Write-Host " # The old ""$taskName"" PowerShell job has been unregistered"; Write-Host;
}
# Uncomment the following exit command to only delete your job.
# exit;
# Shchedule your job. Using of -AtStartup as an example.
$trigger = New-JobTrigger -AtStartup;
$options = New-ScheduledJobOption -StartIfOnBattery -RunElevated;
Write-Host " # Registering of ""$taskName"" job";
Register-ScheduledJob -Name $taskName -Trigger $trigger -ScheduledJobOption $options `
-ScriptBlock {
# Put your code here.
Write-Host Your job has been launched!;
}
$principal = New-ScheduledTaskPrincipal -UserID $accountId `
-LogonType ServiceAccount -RunLevel Highest;
$psJobsPathInScheduler = "\Microsoft\Windows\PowerShell\ScheduledJobs";
$someResult = Set-ScheduledTask -TaskPath $psJobsPathInScheduler `
-TaskName $taskName -Principal $principal
#### End of Main Logic ###########################
Write-Host;
Write-Host " # Let's look at running account of ""$taskName"" PowerShell job"
$task = Get-ScheduledTask -TaskName $taskName
$task.Principal
Write-Host " # Let's start ""$taskName"" manually"
Start-Job -DefinitionName $taskName | Format-Table
Write-Host " # Let's proof that ""$taskName"" PowerShell job has been launched"; Write-Host;
Start-Sleep -Seconds 3
Receive-Job -Name $taskName
Write-Host;
Sadly you can't run schedule a job or task as the system account.
But you can create local administrator accounts as the system account.
And you can schedule jobs or tasks as a local administrator account.
So what I did to get around this problem is this:
$password = ConvertTo-SecureString (New-Guid).Guid -AsPlainText -Force
$user = New-LocalUser "service.scheduler" -Password $Password -Description "For scheduling in tasks from system account"
$credentials = New-Object System.Management.Automation.PSCredential($user.name, $password)
Register-ScheduledJob -Trigger $trigger -ScriptBlock $scriptblock -Name $taskName -ScheduledJobOption $options -credential $credentials
This does mean you are passing in credentials, but you don't have to store them as plain text or specify them.
Sorry, can't make comments with reputation under 50.
Can you use Group Policy to run it as a start up script? That will run as the Local System account. Doesn't look like this cmdlet has the -verb paramater to runas.
Looking at: https://technet.microsoft.com/en-us/library/hh849755.aspx under -ScheduledJobOption there is a setting in there RunElevated=$False, that is the defualt. If you set that to true does it run as admin?
I haven't tried it, it might work.
Hope this helps.
Thanks, Tim.

Powershell run job at startup with admin rights using ScheduledJob

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:

Resources