如何从 Java 程序内部将 powershell 脚本作为 Windows 服务运行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42927184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to run a powershell script as a windows service from inside a Java program?
提问by Manjur
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/]
我有以下代码从 Java 内部运行 Windows 服务。代码使用 JInterop Java 库,JInterop 是 Windows COM 服务器的纯 Java COM 客户端。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)作为服务运行。
回答by Ranadip Dutta
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 commandto 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.
这应该可以解决您的目的。
回答by Ranadip Dutta
You can use SCor New-Serviceto create a Windows Service which,in-turns, can run a ps1file like this:
您可以使用SC或New-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 JAVAand 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,那么你可以直接像Run PS Code as Windows Service 那样做
Hope it helps.
希望能帮助到你。