Saturday, November 14, 2009

Restarting a Remote Service (VBScript vs PowerShell)

This kind of goes along with my rants about PowerShell examples being pretty much reformatted VBScript WMI code examples, but regardless, PowerShell does provide a more abbreviated code environment.  The PowerShell code example was derived from a posting by Thomas Lee on the PowerShell blog on restarting a DNS service on a remote computer.  I had a VBScript example which does the same with the Spooler service, so I simply adapted Thomas’ code to support and apples-to-apples comparison.  As you can see, they are very similar.  In fact, the KiXtart version looks almost identical to both as well.

VBScript Example

strComputer = "server1" 
wscript.echo "Restarting Spooler Service on: ",strComputer

Set wmi = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set ret = wmi.ExecMethod("Win32_Service.Name='Spooler'", "StopService")
If ret.ReturnValue = 0 Then
wscript.echo "Spooler Service stopped"
Else
wscript.echo "Spooler Service not stopped"
End If

Set ret = wmi.ExecMethod("Win32_Service.Name='Spooler '", "StartService")
If ret.ReturnValue = 0 Then
wscript.echo "Spooler Service started"
Else
wscript.echo "Spooler Service not started"
End If


PowerShell Example



$strComputer = "server1" 
"Restarting Spooler Service on: $strComputer"

# get the service object
$svc = gwmi Win32_Service -computer $strComputer | where {$_.name -eq "Spooler"}

# stop the service
$ret = $svc.StopService()
if ($ret.ReturnValue -eq 0) {"Spooler Service stopped"}
else {"Spooler Service not stopped"}

# start the service
$ret = $svc.StartService()
if ($ret.ReturnValue -eq 0) {"Spooler Service started"}
else {"Spooler Service not started"}

2 comments:

  1. Hey, I was wondering if you could maybe offer some help? I'm trying to set up a script very similar to your VBScript to restart services, except I need to be able to use alternate credentials in a domain, so I've tried using "SWbemLocator.ConnectServer", but it always says Access is Denied, even if the account is valid. Any advice for me? I've tried Googling the problem, and no joy :(

    ReplyDelete
  2. There probably a lot of ways to do that. The problem I've encountered is with WMI impersonation, which doesn't seem to ever work like I expect it to. You could wrap the script call in a scheduled task and specify alternate credentials. You could also invoke it via psexec (sysinternals), or something like LsRunAs.exe.

    ReplyDelete