0

I am trying to create the simple reboot task in multiple remote servers with the varying starttime. Here is the powershell script:


   $computers = gc "c:\servers.txt"

   foreach ($computer in $computers)
   {

       icm $computer {SchTasks /Create /SC WEEKLY /D TUE /TN “Reboot Task” /TR “shutdown /r /t 0” /ST 15:00 /RU "SYSTEM"}

   }

For each computer I would like to have the different reboot time. It can be just 5 minutes added to when the loop runs every single time. So 15:00 in first server, 15:05 in second and so on. How can that be done?

1 Answers1

0
$computers = Get-Content "c:\servers.txt"
$timeStart = New-TimeSpan -Hours 15 -Minutes 0
$timeToAdd = New-TimeSpan -Hours  0 -Minutes 5
$sb = {
    param($st)
    if ( SchTasks /Query /TN "Reboot Task" 2>$NULL ) {
        Write-Host SchTasks /Delete /TN "Reboot Task" /F
    }
    Write-Host SchTasks /Create /SC WEEKLY /D TUE /TN "Reboot Task" /TR "shutdown /r /t 0" /ST $st /RU "SYSTEM"
}
foreach ( $computer in $computers ) {
    $timeSTime = $timeStart.ToString( 'hh":"mm')
    $timeStart = $timeStart.Add( $timeToAdd)
    Invoke-Command -ComputerName $computer -ScriptBlock $sb -ArgumentList $timeSTime
}

In the above code snippet:

  • used [System.TimeSpan] objects for easy updating the start time (works over midnight as well), and
  • updated start time is passed to the scriptblock as argument (see this answer), and
  • added an elementary test in the script block (delete the task if already exists) to properly service (supposed) previous attempts, and
  • schtasks commands are merely displayed for debugging.
JosefZ
  • 28,460
  • 5
  • 44
  • 83