Get going with PowerShell


I was scanning through my scripts for PowerShell the other day and I came across a script I was quite fond of back in the day but I can’t remember for the life of me why I wrote it however, I remember using it recently for some mischief! What I wrote was basically a tool for restarting a service against any given host which as you can imagine was used a few times for restarting/stopping MSSQLSERVER on my colleagues PC!

So, without further a-do, the code!!

##################
## FUNCTIONS
##################
function FuncMail
	{#param ($strTo, $strFrom, $strSubject, $strBody, $smtpServer)
	param($To, $From, $Subject, $Body, $smtpServer)
	$msg = new-object Net.Mail.MailMessage
	$smtp = new-object Net.Mail.SmtpClient($smtpServer)
	$msg.From = $From
	$msg.To.Add($To)
	$msg.Subject = $Subject
	$msg.IsBodyHtml = 1
	$msg.Body = $Body
	$smtp.Send($msg)
	}

function FuncRestartService ($server, $service)
{
	$intPingError = 0
	$intError = 0

	$ping = new-object System.Net.NetworkInformation.Ping
	try
		{
			$rslt = $ping.send($server)
		}
	catch
		{
			$intPingError = 1
			$strError = $Error
		}
	if ($intPingError –eq 0) #success: ping
		{
	        write-host “...ping returned, running service restart”
			try
				{
					Restart-Service -InputObject $(Get-Service -Computer $server -Name $service ) -force
				}
			catch
				{
					$intError = 1
					$strError = $Error
				}
			if ($intError -eq 1) #failure: restart - fully exit program
				{
					Write-Host "...an error occurred, notifying by email"
					FuncMail -To $emTo -From $emFrom  -Subject "Server: $server - Error" -Body "$server\$service restart was attempted but failed. Details: $strError" -smtpServer $emSMTP
					break
				}
			else #success: restart
				{
					write-host “...finshed restarting service email sent”
					FuncMail -To $emTo -From $emFrom  -Subject "Server: $server - Restart" -Body "$server\$service has been restarted" -smtpServer $emSMTP
				}
		}
	else #failure: ping - fully exit program
		{
			Write-Host "...ping failed, notifying via email"
			FuncMail -To $emTo -From $emFrom  -Subject "Server: $server - Status" -Body "$server is not responding to ping, please investigate. Details: $strError" -smtpServer $emSMTP
			break
		}
}
##################
## EMAIL Variables
##################
$emTo 		= 'Richard.Thwaites@SomePlace.com'
$emFrom		= 'TMServiceRestart@SomePlace.com'
$emSMTP		= 'AnExchangeServer.com'

##################
## RUN Program
##################
Write-Host "Starting Program..."
Write-Host "...To execute run ""CheckService ServerName"""

FuncRestartService "APCNameHere" "MSSQLSERVER"

Write-Host "...program complete"

If you wanted to you can call two sets of the function if required, suppose you wanted to restart a set of services against an array of servers, a few posts I’ve seen tend to read these in to loops via text files but I prefer the all-in-one way.

Cheers,
Rik

Leave a comment