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

不想你离开。 提交于 2020-01-14 03:50:29

问题


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.


回答1:


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.




回答2:


You can use SC or New-Service to create a Windows Service which,in-turns, can run a ps1 file like this:

sc.exe create "PS1Service" binPath= "powershell.exe -NoLogo -Path D:\Script.ps1"

Reference Link for Creating User Defined Service

Reference Link to Usage of New-Service

This entire thing you can call it from JAVA and that should solve your purpose.

If you have Visual Studio, then you can directly do like Run PS Code as Windows Service

Hope it helps.



来源:https://stackoverflow.com/questions/42927184/how-to-run-a-powershell-script-as-a-windows-service-from-inside-a-java-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!