Restart Windows on certain time

schtasks /create /tn "reboot for updates" /tr "shutdown /r /t 0" /sc once /st 23:27:00 /sd 11/13/2019 /ru "System"

What is this?

Schtasks

Restart Application Pool in Powershell and write it to EventLog

Sometimes on Continuous Integration or other automated scenarios you want to restart Application pool in order to recycle everything clean. This can be done by calling Powershell command Restart-WebAppPool like this: “Restart-WebAppPool AppPoolNameHere”. But you might also want to write log entry to EventLogs so you know what is going on.

In order to write to the event log, one can use the Write-EventLog cmdlet but there are mandatory parameters needed to write the event log information. These are:

  • LogName
  • Source
  • EventID
  • Message

If you want to create an entry log message “Format was called” into the Application Log and store this into your custom source “MyScript” with a custom event ID like “3001”, you will need to type it as:

Write-EventLog -LogName Application -Source MyScript -EventId 3001 -Message "Format was called"

If you have not registered your custom event source, you will encounter an error. In order to register a custom event source, you will need to call the New-EventLog cmdlet like the example below:

New-EventLog -LogName Application -Source MyScript

After this you can call Write-eventLog as following:

Write-EventLog -LogName Application -Source MyScript -EventId 3001 -Message “Format was called”

Restart Windows in 1 hour or certain time

tldr;

  • Open Powershell as Admin
  • Type: Start-Sleep 3600 ; Restart-Computer -Confirm:$false <enter>

 

I work on RDP a lot against Windows Machines and sometimes there are updates and downloads what I need to do and afterwards update. Or perhaps I need to restart in certain time.

Basically what start-sleep does is pause the process for the number of seconds that you specify. The semicolon is like having another line in the code so it will execute what is next, which in this case is restart-computer. Since you may not be logged into the server or it may be at a lock-screen, you will need to include the -confirm:$false otherwise it may not execute.

If you want to restart on certain time

  • shutdown -r -t ([decimal]::round(((Get-Date).AddDays(1).Date.AddHours(3) - (Get-Date)).TotalSeconds))

This will get the number of seconds between the time the script is ran and 3:00AM the following day (on the server time). It then passes the result to shutdown.exe. Obviously this is designed to be ran before midnight. Remember “-r” so it is actually restarting instead of just shutting down.