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.
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
I am trying to create a scheduled task in Powershell which will run a job that uses the active desktop.
1) is my assumption correct that a scheduled task can see the active desktop when it runs?
2) When I execute the following poweshell script, I keep getting an error: Cannot process argument transformation on parameter 'Principal'. Cannot convert value "Servername" to type "Microsoft.Management.Infrastructure.CimInstance"
The code is below:
import-module PSScheduledjob
$TaskStartTime = (Get-Date).AddMinutes(2)
$TaskName = "ExecTestCase"
write-output $TaskStartTime
$action = New-ScheduledTaskAction -Execute "C:\Selenium_Ruby\framework\run_locally_but_update_from_PROD_first.bat"
$trigger = New-ScheduledTaskTrigger -At $TaskStartTime -Once
$principal = "servername\userid" #assume servername \ userid is in quotes
Register-ScheduledTask BatchRunTask -action $action -principal $principal -trigger $trigger
What is wrong?
Also sometimes I get an access denied for the scheduled task too
thanks
The parameter -principal does not accept string input.
Refer to this documentation.
Example:
$STPrin = New-ScheduledTaskPrincipal -GroupId "BUILTIN\Administrators" -RunLevel Highest
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:
I am trying to create a scheduled task that will run a Powershell script with 1 parameter - this is on Server 2012 with Powershell v5 installed. So far I have been able to get the task to run, but it doesn't recognize my param value - the value is null in my script that I am calling. Here is what I have to create the scheduled task:
$TicketTime = "9:00pm"
$EmpID = "1234"
$Firstname = "Test"
$Lastname = "User"
$Action = New-ScheduledTaskAction -Execute "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-ExecutionPolicy ByPass -File C:\Scripts\Term.ps1 -EmpID '$EmpID'"
$Trigger = New-ScheduledTaskTrigger -Once -At "03/29/2016 $TicketTime"
$Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Settings (New-ScheduledTaskSettingsSet)
$Task | Register-ScheduledTask -TaskName "$Firstname $Lastname" -User "myuser" -Password "mypass"
This will execute successfully, but will not recognize the -EmpID parameter. I have also tried -Command instead of -File for the Argument value but I get the same result.
-ExecutionPolicy ByPass -Command "& C:\Scripts\Term.ps1 -EmpID 1234"
Single quotes around the param doesn't seem to do anything either
-ExecutionPolicy ByPass -Command "& C:\Scripts\Term.ps1 -EmpID '1234'"
So far nothing I do will get the param to pass. What am I missing?
Can you try and declare your parameters as positional rather than named:
[CmdletBinding()]
Param (
[Parameter(Position=0)]
[string]$Ticket
)
"-ExecutionPolicy ByPass -File C:\Scripts\Term.ps1 '$EmpID'"
Then you can drop the -ParamName and pass it in using position.
You can use the -File option, you just need to separate out the string:
Change
-ExecutionPolicy ByPass -File "& C:\Scripts\Term.ps1 -EmpID 1234"
to
-ExecutionPolicy ByPass -File "C:\Scripts\Term.ps1" -EmpID "1234"
The full string out look like this:
$Action = New-ScheduledTaskAction -Execute "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-ExecutionPolicy ByPass -File `"C:\Scripts\Term.ps1`" -EmpID `"$EmpID`""
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