PowerShell更新现有计划任务触发器开始日期和时间

t5fffqht  于 2022-11-29  发布在  Shell
关注(0)|答案(3)|浏览(167)

我正在尝试编写一个脚本,该脚本将更新现有任务的触发时间。例如,将开始时间从上午12点更改为凌晨3点。它还需要禁用/启用任务的能力,我目前可以这样做。这是我目前所拥有的。

$servers = gc .\servers.txt

$servers | ForEach-Object {
    $srv = $_
    $schedule = New-Object -Com ("Schedule.Service")
    $schedule.Connect("$srv")
    $tasks = $schedule.GetFolder("\").GetTasks(0)
    $totaltasks = $tasks | where {($_.Name -match $matching1)} #-or ($_.Name -match $matching2)}
    $totaltasks | ForEach-Object {
        if ($status -eq "Disable") {
            $_.Trigger = $triggertime #Daily At 3am
            #$_.Triggers.StartBoundary = "2011-10-01T04:00:00"
            #$_.Enabled = $false
            Write-Host "Disabled Task "$_.Name" for server $srv" -ForegroundColor Yellow
        }

        if ($status -eq "Enable") {
            $_.Enabled = $true
            $_.Triggers.StartBoundary = "2011-10-01T04:00:00 #<--- Does not work
            Write-Host "Enabled Task "$_.Name" for server $srv" -ForegroundColor Green
        }
nhjlsmyf

nhjlsmyf1#

至于你问题的核心......
我正在尝试编写一个脚本,该脚本将更新现有任务的触发时间。
为什么不在此用例中使用内置的cmdlet呢?
Set-Scheduled​Task模块:scheduledtasks修改计划任务。
示例1:修改计划任务中的触发器

$Time = New-ScheduledTaskTrigger -At 12:00 -Once
Set-ScheduledTask -TaskName "SoftwareScan" -Trigger $Time
TaskPath                          TaskName 
--------                          -------- 
\                                 SoftwareScan
avwztpqn

avwztpqn2#

使用以下日期格式:

$_.Triggers.StartBoundary = ('{0:yyyy-MM-dd HH:mm:ss'} -f (Get-Date '10/01/2019 12:33AM'))
# Your Datetime string formatting should expand to: 2019-10-01 00:33:00
jw5wzhpr

jw5wzhpr3#

最好的方法是重新注册您需要的现有任务...

导入xml文件并使用PowerShell 4+计划任务命令,如下所示:

$serverslist_daily_0400 = gc fullyqualifiedpath\inputlist.txt
Foreach($servers in $serverslist_daily_0400){
if($server -like '#*'){continue}
$Stt = New-ScheduledTaskTrigger -Daily -At 4:00am
invoke-command -ComputerName $server -ScriptBlock{
$taskname = (Get-ScheduledTask -TaskPath "\"|where Taskname -like "*reboot*").TaskName #<--this assumes you have reboot in the name
$Stt = New-ScheduledTaskTrigger -Daily -At 4:00am
Set-ScheduledTask -TaskName "$taskname" -Trigger $Stt -Verbose -EA Continue -User domain\svcaccounttorunwith -Password passwordwithnoleadingspecialcharacters } #-Action $sta }
}

相关问题