Function to schedule restart

restartThis monday I had to schedule a restart on a fileserver that weren`t in a cluster, therefore it had to be restarted in the middle of the night. I always have a little trouble when I schedule restarts and have to use google to get it right with the program/script and add argument lines. I decided to create a function where I can specify date and time to schedule the restart. I also put in some other functions as regular expression that checks that date and time is in correct format, deletion of old task with same name, confirmation if you want to create the job and some pop-ups.

#NAME: schedule_restart.ps1
#AUTHOR: Viktor Lindström
#COMMENTS: funtion to schedule restart on local computer.

function Set-restartcomputer 
This function schedules a restart on the local computer
Parameters date and time are mandatory and have to be writen in following formats time = 00(hr):00(mnt):00(sec) and date 0000(year)-00(month)-00(day)
set-restartcomputer -time 16:00:00 -date 2014-09-23
This example creates a scheduled task that restarts the local computer at 16:00:00 the 23 september 2014


$datetime = ($date -as [datetime]).date -replace "00:00:00", $time
$taskname = "RestartComputer"

$job = Get-ScheduledJob -name $taskname -ErrorAction SilentlyContinue

if ($job)
{Unregister-ScheduledJob -name $taskname -ErrorAction SilentlyContinue

$options = New-ScheduledJobOption -RunElevated -StartIfOnBattery
$trigger = New-JobTrigger -Once -At $datetime

$question = ""
while ($question -notmatch "[y|n]"){
    $question = Read-Host "Do you what to schedule a restart of computer at $datetime ? (y/n)"

    if ($question -eq "y"){
    Register-ScheduledJob -name $taskname -ScriptBlock { Restart-Computer -Force } -Trigger $trigger -ScheduledJobOption $options
    $popup = New-Object -ComObject Wscript.Shell
    $popup.Popup("Operation Completed, a restart on computer has been scheduled to $datetime",0,"Done",0x1)
else {$wshell = New-Object -ComObject Wscript.Shell
$wshell.Popup("Run function again",0,"Done",0x1)