opexxx
4/27/2015 - 2:56 PM

restartSophosMessageRouter.ps1

# Clear console screen
clear

# Setup trap to catch exceptions
trap [Exception] {
	Write-Error $("Trapped: " + $_.Exception.Message);
}

# Read computers from the text file
$computers = Get-Content 'C:\servers.txt';
$start = $true;

# Setup the service array with the service names we want to check are running
$serviceArray = 'Sophos Message Router';

foreach($computer in $computers) {
	Write-Host "Checking $computer";
	$objWMIService = Get-WmiObject -Class win32_service -computer $computer
	
	foreach($service in $objWMIService) {
		
		# Check each service specified in the $serviceArray
		foreach($srv in $serviceArray) {
			
			if($service.name -eq $srv) {
				
				Write-Host "$srv is present on $computer.";
				if($service.state -eq "running"){
					
					Write-Host "$srv is running on $computer.";
				}
				else {
					Write-Host "$srv is not running on $computer.";
					# If $start is true the script will attempt to start the service if it is stopped
					if($start -eq $true){
						# Attempt to start the current service on the current computer
						$serviceInstance = (Get-WmiObject -computer $computer Win32_Service -Filter "Name='$srv'");
						$name = $serviceInstance.Name;
						Write-Host "Attempting to start $name on $computer."
						$serviceInstance.StartService() | Out-Null;
						# Refresh the object instance so we get new data
						$serviceInstance = (Get-WmiObject -computer $computer Win32_Service -Filter "Name='$srv'");
						$state = $serviceInstance.State;
						Write-Host "$name is ""$state"" on $computer.";
						#Start-WebSite 'ECS';
					}					
				}				
			}
		}
	}
}

Write-Host "`n";