简体   繁体   English

如何从Java程序内部运行PowerShell脚本作为Windows服务?

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

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. 我有以下代码从Java内部运行Windows服务。代码使用JInterop Java库,JInterop是Windows COM服务器的纯Java COM客户端。 More details of JIntop are available here [ http://fishi.devtail.io/weblog/2015/01/21/pure-java-dcom-bridge-j-interop/] 有关JIntop的更多详细信息,请访问[ 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. 是否可以使用相同的库或以其他方式以与上述相同的方式将powershell文件(.ps1)作为服务运行。

You can create a batch file which, in-turns, can trigger a powershell script like this: 您可以创建一个批处理文件,反过来,它可以触发PowerShell脚本,如下所示:

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

Save it as "Trigger_ps.bat" 将其另存为“Trigger_ps.bat”

Then you can use the sc command to create a windows service by mentioning this batch file path like this: 然后,您可以使用sc命令创建一个Windows服务,方法是提到这个批处理文件路径,如下所示:

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

This should solve your purpose. 这应该可以解决你的目的。

You can use SC or New-Service to create a Windows Service which,in-turns, can run a ps1 file like this: 您可以使用SCNew-Service创建Windows服务,然后可以运行这样的ps1文件:

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. 这一切你可以从JAVA称之为,这应该可以解决你的目的。

If you have Visual Studio, then you can directly do like Run PS Code as Windows Service 如果您有Visual Studio,那么您可以直接执行像运行PS代码作为Windows服务

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM