-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRestart-ComputerAndSendEmail.ps1
59 lines (51 loc) · 2.34 KB
/
Restart-ComputerAndSendEmail.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Restart-ComputerAndSendEmail.ps1
# Purpose: Reboot local or remote PC right after sending an email announcing the reboot.
# Originally intended to be run by a scheduled task.
# Notes:
# * As a precaution, "-WhatIf" is included below to prevent reboots until after testing.
# * To restart the local PC: Restart-Computer -Force
# * To restart a remote PC: Restart-Computer -ComputerName Name1, Name2, Name3 -Force -Wait -For PowerShell -Timeout 300 -Delay 2
# References:
# * https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/restart-computer?view=powershell-5.1
# Setup variables
$scriptPath = "$($PSScriptRoot)\$($MyInvocation.MyCommand)"
$emailUsername = "[email protected]"
$emailPassword = "CHANGEME"
$emailSMTP = "smtp.mandrillapp.com"
$emailPort = 587
# Custom variables
$rebootDelayInSeconds = 60
$emailFrom = "[email protected]"
$emailTo = "[email protected],[email protected]"
$emailSubject = "Reboot: $env:ComputerName"
$emailBody = @()
# Set the body of the email
$emailBody += "Server $env:ComputerName will reboot in $rebootDelayInSeconds seconds."
$emailBody += "Trigger: Scheduled Task"
$emailBody += "Script: $scriptPath"
$emailBody = $emailBody -join "`n`n"
Write-Output " * Email details:"
Write-Output "username: '$emailUsername'"
Write-Output "password: '[REDACTED]'"
Write-Output "server: '$emailSMTP'"
Write-Output "port: '$emailPort'"
Write-Output "from: '$emailFrom'"
Write-Output "to: '$emailTo'"
Write-Output "subject: '$emailSubject'"
Write-Output "body:"
Write-Output "---"
Write-Output "$emailBody"
Write-Output "---"
Write-Output " * Sending email"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($emailFrom, $emailTo, $emailSubject, $emailBody)
$SMTPClient = New-Object Net.Mail.SmtpClient($emailSMTP, $emailPort)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($emailUsername, $emailPassword)
$SMTPClient.Send($SMTPMessage)
Write-Output " * Email sent"
Write-Output " * Waiting $rebootDelayInSeconds seconds"
Start-Sleep -Seconds $rebootDelayInSeconds
# WARNING: Remove "-WhatIf" only after testing
Write-Output " * Rebooting"
Restart-Computer -Force -WhatIf
# Restart-Computer -ComputerName Name1, Name2, Name3 -Force -Wait -For PowerShell -Timeout 300 -Delay 2 -WhatIf