在powershell中(不管是不是管理员),C:\Users\mine\Desktop\LOL\test.ps1在没有schtasks的情况下可以正常工作,但是当我用它创建schtasks时,它就不能工作了。什么都没发生。
test.ps1可以在powershell中正常运行。
当我查询schtasks时,"Backup DB“显示状态为ready。
假设我将其设置为10:08。当我在10:08之前查询时,下一个运行时是今天的10:08。当我查询10:08之后,下一个运行时间是tomorrow 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
发布于 2019-01-29 12:17:18
您的任务创建很好。因为您没有调用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" 希望能有所帮助。
https://stackoverflow.com/questions/54413456
复制相似问题