通过Powershell 创建一个COM 对象, 并使用创建出的COM 对象自带的属性和方法来创建本地或者远程计算机的任务计划,其中Script 由自己的实际业务需要设定相关的逻辑


[ScriptBlock]$Script = { Get-Service | select -First 1 | Out-File D:\test.log -Encoding utf8 }

$User = [Security.Principal.WindowsIdentity]::GetCurrent()


$Scheduler = New-Object -ComObject Schedule.Service

$Task = $Scheduler.NewTask(0)

[string]$TaskName = "PSWindowsUpdate"

$RegistrationInfo = $Task.RegistrationInfo

$RegistrationInfo.Description = $TaskName

$RegistrationInfo.Author = $User.Name


$Action = $Task.Actions.Create(0)

$Action.Path = "powershell"

$Action.Arguments = "-Command $Script"


# http://woshub.com/how-to-create-scheduled-task-using-powershell/

$Triggers = $Task.Triggers.Create(1)

$triggerstart = Get-Date -Hour 14 -Minute 0 -Second 0

$triggersend = $triggerstart.AddHours(1)

$Triggers.StartBoundary = [string]($triggerstart.ToString("yyyy-MM-dd'T'HH:mm:ss"))

$Triggers.EndBoundary = [string]($triggersend.ToString("yyyy-MM-dd'T'HH:mm:ss"))


$Settings = $Task.Settings

# https://docs.microsoft.com/en-us/windows/win32/taskschd/taskschedulerschema-deleteexpiredtaskafter-settingstype-element

$Settings.DeleteExpiredTaskAfter = "PT1H" # auto expired and deleted itself after 1 Hour

$Settings.Enabled = $True

$Settings.StartWhenAvailable = $True

$Settings.Hidden = $False


$Task.Principal.RunLevel = 1

$Scheduler.Connect($env:COMPUTERNAME)

$RootFolder = $Scheduler.GetFolder("\")

$RootFolder.RegisterTaskDefinition($TaskName, $Task, 6, "SYSTEM", $Null, 1)