K
K
Kadet77Rus2017-11-10 12:01:06
cmd/bat
Kadet77Rus, 2017-11-10 12:01:06

How to check for the presence of a service and if it is not there, run a batch file?

Greetings. There is a certain exe-shnik that I would like to run on all computers in the domain when turned on. At the moment, I could only implement this as a logon script through GPO in this way: the first batch file lies in the autorun and launches vbs, which, in turn, already creates its own hidden shell and launches an exe file with arguments there. To make it clear, here is the script:
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "cmd.exe /c %path_to_folder%\start.bat", 0, false
The service is created and started manually using nssm. The automation of this process seems to me something like this -
1) Distribute the necessary files through the GPO
2) Push a script into the autorun that checks for the presence of the service, and, in case of its absence, launches nssm with the installation parameters. Question - how to do it? In PowerShelle and VBS, I'm not strong, unfortunately

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
res2001, 2017-11-10
@res2001

From cmd, you can check the status of the service with sc and parse its output.
Or you can use tasklist to display a list of running processes and find the one you need, if it is not there, then the service is not running.
You can start any process as a service using srvany and instrvs. These utilities are included with Microsoft's Windows Server 2003 Resource Kit. They worked quite well on Win7, they don’t know further.

A
Alexander Slyzhuk, 2017-11-10
@SLYzhuk

it's easier to terminate the service and then start than to monitor

N
NRinat, 2017-11-12
@NRinat

Option 1
Approximately you can use this function.

Function ServiceExists([string] $ServiceName) {
    [bool] $Return = $False
    if ( Get-WmiObject -Class Win32_Service -Filter "Name='$ServiceName'" ) {
        $Return = $True
    }
    Return $Return
}

Then check and run the command
if (!ServiceExists ServiceName)
{
    run some command
}

Option 2
if (!Get-Service "ServiceName" -ErrorAction SilentlyContinue)
{
    run some command
}

Option 3
I would probably make a better wmi filter for GPO and tie it to politics, such a feeling that it will be more reliable.
PS!
I have not tested the examples, use them at your own peril and risk)))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question