how to run a powershell script as a windows service from inside a Java program?
Asked Answered
T

1

1

I have the following code that runs a windows service from inside Java.The code uses JInterop Java library, JInterop is a pure Java COM client for windows COM server. More details of JIntop are available here [http://fishi.devtail.io/weblog/2015/01/21/pure-java-dcom-bridge-j-interop/]

    String cmdFile = "service.bat";
results = wbemServices_dispatch.callMethodA(
                "Get", new Object[]{ new JIString("Win32_Process"),
                new Integer(0), JIVariant.OPTIONAL_PARAM()});

        IJIDispatch wbemObjectSet_dispatch = (IJIDispatch)JIObjectFactory.narrowObject(
                (results[0]).getObjectAsComObject());
results = wbemObjectSet_dispatch.callMethodA("Create",
                new Object[]{ new JIString(targetFilePrefix + cmdFile),
                JIVariant.OPTIONAL_PARAM(),
                JIVariant.OPTIONAL_PARAM()});

Is it possible to run a powershell file(.ps1) as a service in the same manner as above using the same library, or in some other way.

Tales answered 21/3, 2017 at 12:28 Comment(0)
S
5

You can create a batch file which, in-turns, can trigger a powershell script like this:

@echo off
Powershell.exe set-executionpolicy remotesigned -File  C:\folder\MyScript.ps1
pause

Save it as "Trigger_ps.bat"

Then you can use the sc command to create a windows service by mentioning this batch file path like this:

SC CREATE PS_Trigger_Service Displayname= "PS_Trigger_Service" binpath= "C:\folder\Trigger_ps.bat" start= auto

This should solve your purpose.

Stimulant answered 23/3, 2017 at 7:5 Comment(2)
can I create and then start/stop/delete this service in a remote machine?Tales
For sure , you can do that. @TalesStimulant

© 2022 - 2024 — McMap. All rights reserved.