I'm trying to create a new Windows Scheduler Task, which will run some sync job.
The things are:
I want to use a separated service account, not Administrator
I want to run a job not to get tied with service account's password change. In Windows Scheduler Task it is a "Do not store password" check button ("-LogonType S4U" option below)
Job should be created by Powershell as job creation should be automated
I'm running commands below under local Administrator and get an error:
PS C:\Temp> $TaskAction = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "<ARGUMENTS>"
PS C:\Temp> $TaskSettingsSet = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Hours 3) -MultipleInstances IgnoreNew -DontStopIfGoingOnBatteries
PS C:\Temp> $TaskTrigger = New-ScheduledTaskTrigger -RandomDelay (New-TimeSpan -Minutes 40) -Weekly -DaysOfWeek Saturday -At 7:30am
PS C:\Temp> $TaskPrincipal = New-ScheduledTaskPrincipal -UserId "<SERVICE_USER>" -LogonType S4U
PS C:\Temp> Register-ScheduledTask -Action $TaskAction -Description "<DESC>" -Settings $TaskSettingsSet -Principal $TaskPrincipal -TaskName "<TASK_NAME>" -TaskPath "\" -Trigger $TaskTrigger
Register-ScheduledTask : Access is denied.
At line:1 char:1
+ Register-ScheduledTask -Action $TaskAction -Description "<DESC>" ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (PS_ScheduledTask:Root/Microsoft/...S_ScheduledTask) [Register-ScheduledTask], CimException
+ FullyQualifiedErrorId : HRESULT 0x80070005,Register-ScheduledTask
<SERVICE_USER> has been added to "Log on as a batch job" local policy.
Permissions for C:\Windows\Tasks or C:\Windows\System32\Tasks set with iCACLS does not help.
I've even added <SERVICE_USER> to local Administrators group - the same error.
If I do everything via GUI - it asks me <SERVICE_USER> credentials and works fine.
What permissions do I lack?
The thing was in user, running PS: if your need a "Do not store password" check button in your job, you need all the code above in PS console being ran under <SERVICE_USER> (you need to add <SERVICE_USER> to "Allow log on locally" local policy).
An Ansible example:
- name: Create and register sync task
win_shell: |
$TaskAction = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "<ARGUMENTS>"
$TaskSettingsSet = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Hours 3) -MultipleInstances IgnoreNew -DontStopIfGoingOnBatteries
$TaskTrigger = New-ScheduledTaskTrigger -RandomDelay (New-TimeSpan -Minutes 40) -Weekly -DaysOfWeek Saturday -At 7:30am
$TaskPrincipal = New-ScheduledTaskPrincipal -UserId "<SERVICE_USER>" -LogonType S4U
Register-ScheduledTask -Action $TaskAction -Description "<DESC>" -Settings $TaskSettingsSet -Principal $TaskPrincipal -TaskName "<TASK_NAME>" -TaskPath "\" -Trigger $TaskTrigger
vars:
ansible_become: yes
ansible_become_method: runas
ansible_become_user: <SERVICE_USER>
register: sync_task
Related
I am trying to automate creation of system restore points using Powershell (v7.2.6). Following are the commands that I have run:
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument 'ExecutionPolicy Bypass -Command "Checkpoint-Computer -Description \"Auto Backup\" -RestorePointType \"MODIFY_SETTINGS\""'
$trigger = New-ScheduledTaskTrigger -Weekly -At 9am
$stsettings = New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -StartWhenAvailable
These work fine but when I run...
Register-ScheduledTask -TaskName "Auto System Backup" -RunLevel Highest -Action $action -Trigger $trigger -Settings $stsettings
...I get the an error message: Register-ScheduledTask: The parameter is incorrect.
Not sure which parameter is incorrect though. What am I doing wrong here?
The below command is wrong. There is no -Monthly parameter in New-ScheduledTaskTrigger. Also what you have specified does not make sense, Monthly 9am??
$trigger = New-ScheduledTaskTrigger -Monthly -At 9am
$taskTrigger1 = New-ScheduledTaskTrigger -Once -At 2:50PM
$taskAction = New-ScheduledTaskAction `
-Execute "powershell.exe" `
-Argument "-ExecutionPolicy ByPass -File `"<path>\tiddlywikiIIS_schtask_rsync\backup.ps1`""
$taskName = "Backup Stuff"
$description = "Rsync Backup Stuff"
Register-ScheduledTask `
-TaskName $taskName `
-Action $taskAction `
-Trigger $taskTrigger1 `
-Description $description
$taskPrinciple = New-ScheduledTaskPrincipal -UserId "Domain\someadmin" -RunLevel Highest
$taskSettings = New-ScheduledTaskSettingsSet -Compatibility Win8
Set-ScheduledTask -TaskName $taskName -Principal $taskPrinciple -Settings $taskSettings
Set-ScheduledTask -TaskName $taskName -User $taskPrinciple.UserID -Password '******'
# Pull the creds for a user account that has WSL installed on it.
$cred = Get-StoredCredential -Target "some-non-admin-credz"
$psi = New-Object System.Diagnostics.ProcessStartInfo -Property #{
RedirectStandardError = $true
RedirectStandardOutput = $true
UseShellExecute = $False
UserName = $cred.GetNetworkCredential().Username
Domain = $cred.GetNetworkCredential().Domain
Password = $cred.Password
WorkingDirectory = "C:\windows\"
FileName = "wsl"
Arguments = "-d Ubuntu-18.04 -e rsync -av --delete /mnt/c/stuff/ /mnt/o/stuff_bk/"
WindowStyle = "Hidden"
}
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $psi
$p.WaitForExit()
$p.ExitCode
backup.ps1
I have the code above running in a scheduled task that is running with an (domain?) administrator account.
When it returns from the scheduled task it's $p.ExitCode is -1073741502 but if I run the same code in an administrative powershell prompt run as the same (domain?) administrative account it runs fine.
It makes me thing that it has something to do with the Local Security Policy as I remember there being some sort of "Allow Batch Execution" or "Delegate" or some such privilege in there that prevents any group or user not included from running something as a batch job.
I also found the following log in the Event Viewer:
Okay, so I found a log entry in the System Log with a Source of Application Popup, Event ID 26 which reads:
EventData -> Caption: `wsl.exe - Application Error`
EventData -> Message: `The application was unable to start correctly (0xc0000142). Click OK to close the application.`
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 am creating a PowerShell script which will create a scheduled task.
Using the Windows GUI, in the settings dialogue, I can set it to "Stop the existing instance" which will close the program if it's already running.
When exporting this task via XML the field is labelled as:
<Settings>
<MultipleInstancesPolicy>StopExisting</MultipleInstancesPolicy>
</Settings>
However, when writing this in PowerShell I only have the options for IgnoreNew, Parallel and Queue.
Is there a way to use the StopInstace via PowerShell?
Here is my code:
$Action = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument "/c 'command'"
$Trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionDuration (New-TimeSpan -Days (365 * 20)) -RepetitionInterval (New-TimeSpan -Minutes 33)
**$Setting = New-ScheduledTaskSettingsSet -MultipleInstances StopInstance**
Register-ScheduledTask -Action $Action -Trigger $Trigger -Setting $Setting -TaskName "Microsoft Windows > Monitoring Service" -Description "Command Runner"
The StopInstance enum value currently is not supported by ScheduledTasks module.
You can directly set CIM property value instead:
$Action = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument "/c 'ver'"
$Trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionDuration (New-TimeSpan -Days (365 * 20)) -RepetitionInterval (New-TimeSpan -Minutes 33)
$Setting = New-ScheduledTaskSettingsSet
$Setting.CimInstanceProperties.Item('MultipleInstances').Value = 3 # 3 corresponds to 'Stop the existing instance'
Register-ScheduledTask -Action $Action -Trigger $Trigger -Setting $Setting -TaskName "Microsoft Windows > Monitoring Service" -Description "Command Runner"
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: