Skip to content

Instantly share code, notes, and snippets.

@silverskymedia
Created March 8, 2012 16:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save silverskymedia/2001719 to your computer and use it in GitHub Desktop.
Save silverskymedia/2001719 to your computer and use it in GitHub Desktop.
PowerShell: Check Services
# 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 = 'IISADMIN';
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";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment