(无论是否为管理员),C:\Users\mine\Desktop\LOL\test.ps1
都可以在没有schtasks
的情况下正常工作,但是当我使用它创建schtasks
时,它就无法工作。什么都没发生。
test.ps1
可以在Powershell中正常运行。
当我查询schtasks
时,出现“备份数据库”,状态为就绪。
假设我将其设置为10:08
。
当我在10:08
之前查询时,下一个运行时间是今天10:08
。
当我在10:08
之后查询时,下一个运行时间是明天10:08
,
但两者之间什么也没发生。
PS C:\Users\mine> Schtasks /create /tn "Backup DB" /sc daily /st 10:08 /tr "C:\Users\mine\Desktop\LOL\test.ps1"
WARNING: The task name "Backup DB" already exists. Do you want to replace it (Y/N)? y
SUCCESS: The scheduled task "Backup DB" has successfully been created.
简而言之,我想每天使用powershell运行test.ps1
答案 0 :(得分:0)
您的任务创建很好。由于您没有调用powershell.exe来调用.ps1,因此从技术上讲,它仅像记事本文件一样调用.ps1。
$TaskName = "Backup DB"
$TaskDescr = "Automated Backup DB"
$TaskCommand = "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe"
$TaskScript = '"C:\Users\mine\Desktop\LOL\test.ps1"+'"'
$TaskArg = "-Executionpolicy unrestricted -file $TaskScript"
$service = new-object -ComObject("Schedule.Service")
# connect to the local machine.
$service.Connect()
$rootFolder = $service.GetFolder("\")
$TaskDefinition = $service.NewTask(0)
$TaskDefinition.RegistrationInfo.Description = "$TaskDescr"
$TaskDefinition.Settings.Enabled = $true
$TaskDefinition.Settings.AllowDemandStart = $true
$TaskDefinition.Settings.StartWhenAvailable = $true
$TaskDefinition.Settings.StopIfGoingOnBatteries=$false
$TaskDefinition.Settings.DisallowStartIfOnBatteries=$false
$TaskDefinition.Settings.MultipleInstances=2
$taskdefinition.Settings.WakeToRun=$true
$triggers = $TaskDefinition.Triggers
$trigger = $triggers.Create(1) # Creates a "One time" trigger
$trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss")
$time_interval=New-TimeSpan -Minutes $interval
$time_interval=$time_interval.TotalSeconds
$trigger.Repetition.Interval= "PT"+"$time_interval"+"S"
$trigger.Enabled = $true
$TaskDefinition.Principal.RunLevel =1
$Action = $TaskDefinition.Actions.Create(0)
$action.Path = "$TaskCommand"
$action.Arguments = "$TaskArg"
# In Task Definition,
# 6 indicates "the task will not execute when it is registered unless a time-based trigger causes it to execute on registration."
# 5 indicates "Indicates that a Local System, Local Service, or Network Service account is being used as a security context to run the task.In this case, its the SYSTEM"
$rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5) | Out-Null
我添加了相应的注释以相应地创建任务和触发器。
替代方法是像这样直接使用Powershell:
Import-Module TaskScheduler $task = New-Task
$task.Settings.Hidden = $true
Add-TaskAction -Task $task -Path C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe –Arguments “-File C:\Users\mine\Desktop\LOL\test.ps1”
Add-TaskTrigger -Task $task -Daily -At “10:06”
Register-ScheduledJob –Name ”Monitor Group Management” -Task $task
直接方法:
C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NonInteractive -File "C:\Users\mine\Desktop\LOL\test.ps1"
希望有帮助。