Forum Discussion

Oferv's avatar
Oferv
Super Contributor
14 years ago

STOP/START service

Hi,



is there a way to stop/start a service using C#Script?



i found this link http://smartbear.com/support/viewarticle/9044/ but, when i add it to a unit i added under a C#Script i'm getting an error message.



is there an other/easy way to do that?and if not why do i get expected ";" message right after the first Sub?



Thanks
  • tristaanogre's avatar
    tristaanogre
    Esteemed Contributor
    The link has JScript syntax for the same thing.  Use this for your C#Script.



    function Test() 

    {

    StopService(".", "TestComplete 7 Service");

    Delay(10000);

    StartService(".", "TestComplete 7 Service");

    }


    function StartService(computerName, serviceName)

    {

    var service = GetService(computerName, serviceName);

    if (service == null) {

    Log.Warning("The " + serviceName + " service on the " + computerName +

    " computer was not found");

    }

    else

    service.StartService();

    }


    function StopService(computerName, serviceName)

    {

    var service = GetService(computerName, serviceName);

    if (service == null) {

    Log.Warning("The " + serviceName + " service on the " + computerName +

    " computer was not found");

    }

    else

    service.StopService();

    }


    function GetService(computerName, serviceName)

    {

    var wmiService, objectsList, eObjectsList, item, sysID;

    wmiService = GetObject("WinMgmts:{impersonationLevel=impersonate}!\\\\" +

    computerName + "\\root\\cimv2");

    objectsList = wmiService.InstancesOf("Win32_Service");

    if (objectsList.Count > 0) {

    eObjectsList = new Enumerator(objectsList);

    for (; !eObjectsList.atEnd(); eObjectsList.moveNext()) {

    item = eObjectsList.item();

    if (item.Name == serviceName)

    return item;

    }

    }

    return null;

    }
  • tristaanogre's avatar
    tristaanogre
    Esteemed Contributor
    VBScript is an entirely different syntax than C#Script so they are incompatible.



    However, for TestComplete, C#Script, C++Script, and JScript all use the same parsing/syntax engine for interpreting code.  You can write using C# syntax or JScript syntax and TC works with either one.
  • tristaanogre's avatar
    tristaanogre
    Esteemed Contributor
    What script are you pasting in?  There's no "subs" in C#Script... I'm assuming you copied in the JScript code from that article.



    What exactly is the error message you're getting and on what line of code?
  • Oferv's avatar
    Oferv
    Super Contributor
    yes that's what i did.

    i need to stop a service and i didn't find any other way to do that except the example you gave which is in VBScript and i copied it.

    the error message i'm getting is - see attached file
  • Oferv's avatar
    Oferv
    Super Contributor
    Hoo cool thanks didn't know that JS can work with C#Script and VBS can't

    Thanks