Using PowerShell and WMI to change Service settings

Recently we had a situation where a service would not start on initial boot up. The service could be started manually after the server had started so it was not a problem with the service or the account that it was running under. I had already tried setting the Startup Type to be Automatic (Delayed Start) but this did not allow the service to start after a reboot. I then checked the Recovery tab for the service and saw that all options were set to Take No Action. Since one of the recovery options is Restart the Service and another is Restart the Server, I decided to look to see if there was a way to programmatically set this to remove human error from the equation. Automation is always the best way to go to ensure that the same process is repeated each time.

I want to do this in PowerShell so the snippet can be added to our build scripts. This will work for any service but I am specifically trying to set the Recovery options for the SQL Agent. I found the Get-Service cmdlet within PowerShell but was not able to set access/set/update this value within the service. I then began looking at WMI options and came across sc.exe.  I found this great blog post that addressed the exact problem I was working on. Check it out for all of the information related to the arguments in my code snippet.

Here is the snippet that I used to update this setting.

$services = Get-WMIObject win32_service  | ? {$_.name -eq “SQLSERVERAGENT” -and $_.startmode -eq “Auto”}
foreach ($service in $services){sc.exe failure $service.name reset= 86400 actions= restart/5000}

I hope this helps you if you run across the need to perform this as well.

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Terri is a Microsoft MVP (ASP .NET/IIS), an MCSA: Windows Server 2012, and a Support Specialist at OrcsWeb, a hosted server company providing managed hosting solutions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: