Send email alert if Reboot or shutdown a Server with Powershell

Présentation


This script allows to send a status mail when a server restarts or stops. All actions are logged to C:\Logs.

Github Link : 

Exécution command line for reboot status : 
  • powershell.exe -executionpolicy ByPass -file .\ScriptName.ps1 -Option Reboot
Exécution command line for shutdown status : 
  • powershell.exe -executionpolicy ByPass -file .\ScriptName.ps1 -Option Shutdown

#Script Parameters
Param(
[Parameter(Mandatory=$true)]
[ValidateSet("Reboot", "Shutdown")]
[String[]]
$Option
)

#Function create Log folder
    Function CreateLogsFolder
{
    If(!(Test-Path C:\Logs))
    {
    New-Item -Force -Path "C:\Logs\" -ItemType Directory
}
else
{
    Write-Host "The folder "C:\Logs\" already exists !"
    }
}

#Create Log Folder
    CreateLogsFolder

#Declaration of script variables
    $Client = "Client Name"
    $Server = (Get-CimInstance -ClassName Win32_ComputerSystem).Name
    $Date = Get-Date
    $LogPath = "C:\Logs\StateServer.log"

# Define the email address to send notifications to
    $to = "YourEmailAdress"
    $to2 = "OtherEmailAdress"

If ($Option -eq "Reboot")
{
#Send the notification
    Write-Output "$($Date) Send alert email to $($to) and $($to2) : The server $Server has rebooted." | Tee-Object -FilePath $LogPath -Append
Send-MailMessage -To $($to;$to2) -From "SenderEmailAdress" -SmtpServer SmtpAdress -Subject "$Client - $Server - Server Reboot" -Body "The server $Server has rebooted."
}

If  ($Option -eq "Shutdown")
{
#Send the notification
    Write-Output "$($Date) Send alert email to $($to) and $($to2) : The server $Server has been shutdown." | Tee-Object -FilePath $LogPath -Append
Send-MailMessage -To $($to;$to2) -From "SenderEmailAdress" -SmtpServer SmtpAdress -Subject "$Client - $Server - Server Shutdown" -Body "The server $Server has been shutdown."
}


Configuration

To facilitate the deployment, it is preferable to create a GPO in the following way :
  • Open Group Policy Strategy MMC
  • Select Create New GPO
  • Go to Computer Configuration \ Strategy \ Windows Parameters \ Script (Restart / Shutdown)
  • In the Scripts Powershell Tab, add your script with this paramters : 
    • "-Option Reboot"


  • Repeat all actions for Shutdown script and replace the paramters with "-Option Shutdown"

Result

When the server restarts, an alert email will be sent to you :



For Shutdown alert


Popular posts from this blog

How to implement Applocker with Microsoft Intune

How to reset computer in OOBE mode

Microsoft Intune, Uninstall Win32 app with the company portal