Skip to content

Instantly share code, notes, and snippets.

@istairbn
Created October 20, 2015 13:24
Show Gist options
  • Save istairbn/55010e9056263a83a698 to your computer and use it in GitHub Desktop.
Save istairbn/55010e9056263a83a698 to your computer and use it in GitHub Desktop.
This Powershell script returns a Windows service to Automatic mode and restarts it if it was stopped
#------------------------------------------------------------------------------
#Script: KeepItAuto.ps1
#Author: Benjamin Newton - Excelian
#Version 1.0.0
#Keywords: DesiredState,Environment Management
#Comments:This script keeps services on Automatic and Alive!
#-------------------------------------------------------------------------------
<#
.Synopsis
This script takes a list of service names. If those services have been set to Manual, it turns them automatic. It then turns them on.
.Parameter ServiceNames
The services to keep alive
#>
Param(
[CmdletBinding()]
[Parameter (Mandatory=$False)]
[string[]]
$ServiceNames = ('Logscape Agent')
)
Foreach ($SName in $ServiceNames){
Try{
$Service = Get-Service -Name $SName
$WMIService = Get-WmiObject -Class Win32_Service -Property StartMode -Filter "Name='$SName'"
}
Catch [System.Exception]{
Write-Error $Error.ToString()
$Error.Clear()
}
Try{
If($WMIService.StartMode -eq 'Auto'){
Write-Verbose "$SName : Already Automatic"
}
Else{
Set-Service $Service.Name -StartupType Automatic
Write-Output "$SName : Switched to Automatic"
}
}
Catch [System.Exception]{
Write-Error $Error.ToString()
$Error.Clear()
}
Try{
If($Service.Status -eq "Running"){
Write-Verbose "$SName : Already Running"
}
Else{
Start-Service $Service.Name
Write-Output "$SName : Starting Service"
}
}
Catch [System.Exception]{
Write-Error $Error.ToString()
$Error.Clear()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment