Schedule Reboot With Powershell Script

Using the Script provided below you can schedule a VM reboot to allow for updates or policy implementation. How to steps are located right below the script

Powershell SCRIPT: ScheduledReboot.ps1 

 

# Define maximum attempts 

$max_Attempts = 5 #Adjust retry attempts as per your need 

$attempts = 0 

 

# Function to check if a user is logged in 

function IsUserLoggedIn { 

   #only capture active session, ignoring disconnected sessions  

    $users = quser | Select-String "Active" 

    return $users -ne $null 

} 

 

# log activity 

function Log-Activity { 

    param ( 

        [string]$Message 

    ) 

    $logPath = "C:\ScheduleRebootLogs\RebootScript.log" 

    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" 

    "$timestamp - $Message" | Out-File -Append -FilePath $logPath 

} 

 

# log directory exists 

if (!(Test-Path "C:\ScheduleRebootLogs")) { 

    New-Item -Path "C:\Logs" -ItemType Directory 

} 

 

Log-Activity "Starting scheduled reboot script." 

 

# Attempt to reboot up to “max_Attempts” times 

while ($attempts -lt $max_Attempts) { 

    if (IsUserLoggedIn) { 

        Log-Activity "User is logged in. Skipping reboot attempt $($attempts + 1)." 

        Start-Sleep -Seconds 900 # Wait 15 mins before retrying 

    } else { 

        Log-Activity "No user is logged in. Rebooting now." 

        Restart-Computer -Force 

        break 

    } 

    $attempts++ 

} 

 

if ($attempts -ge $maxAttempts) { 

    Log-Activity "Max attempts reached. Exiting script." 

} 

 

Log-Activity "Reboot script execution completed."

  1. Prepare the PowerShell Script 

  • Save the ScheduledReboot.ps1 script and copy to a share location \\<DomainName>\SYSVOL\<DomainName>\Scripts\ScheduledReboot.ps1 from where the script is accessible to all machine in the domain and has Read & Execute permissions for the Domain Computers (DC). 

    • Note: Sysvol path on DC is “C:\windows\SYSVOL\sysvol\<domain>scripts” 

 

  1. Create a scheduled task (scheduled job) policy using the Group Policy Management Console : 

Open Group Policy Management 

  • On the domain controller or a machine with the necessary permissions, open Group Policy Management: 

  • Press Win + R, type gpmc.msc, and press Enter. 

  • Navigate to the Organizational Unit (OU) where your target machines are located. 

  • Example: Domain > Example.com > Organizational Units > Target VMs. 

  • Right-click the OU and create a new GPO. Name the policy (e.g., "RestartVMNoUserPolicy") and then edit it. 

 

Navigate to the Scheduled Tasks Configuration 

  • In the Group Policy Management Editor, Go to Computer Configuration > Preferences > Control Panel Settings > Scheduled Tasks. 

  • Right-click on Scheduled Tasks in the right pane and select New > Scheduled Tasks. 

 

  1. Configure the Scheduled Task 

  • General Tab: 

  • Action: Create 

  • Name: Enter a descriptive name for the task (e.g., "RestartVMIfNoUser"). 

  • Description: Add a meaningful description (e.g., "Restarts VM if no user is logged in"). 

  • Select the BUILTIN\Administrators or an appropriate service account, with permission to reboot domain machines. 

  • Security Options: 

  • Select Run whether user is logged on or not. 

  • Select Run with highest privileges. 

  

  • Triggers Tab: 

  • Click New to create a trigger. 

  • Configure the trigger: 

  • Set the task to run at daily/weekly as needed. 

  • Adjust the delay or repeat interval as required. 

 

  • Actions Tab: 

  • Click New to create an action. 

  • Configure the action: 

  • Action: Start a program. 

  • Program/script:  

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Executionpolicy Bypass -WindowStyle hidden  

  • Add Arguments:  

-File "\\<domain>\SYSVOL\<domain>\scripts\ScheduledReboot.ps1"  

 

  • Conditions Tab: 

  • Adjust the Conditions as required. 

 

  • Settings Tab: 

  • Check Allow task to be run on demand. 

  • Adjust the settings as required. 

 

  1. Apply and test the GPO 

  • Close the Group Policy Management Editor to save the changes. 

  • Link the GPO to the desired OU if it isn’t already linked. 

 

Note: Do validate the Policy Security filter, which group of users, groups and Computers selected. 

 

  • Restart or force GPO Update on Target Machines by running “gpupdate /force” 

 

 

  1. Verify the Task Deployment 

  • On a target VM, confirm that the task runs successfully by verifying logs in Event Viewer > Windows Logs > System.